-3

I have 2 forms which consist of:

Form1:

2buttons named: btnCopy and btnPaste (with functions inside like rtb.Copy(); and rtb.Paste(); that should work for richtextbox in Form2)

Form2:

1richtextbox named: rtb

My question was: How can I communicate between the 2buttons from Form1 (with its functions) and the richtextbox in Form2.

like: When I type text inside richtextbox(rtb) in Form2 then i SelectAll text then I Press the CopyButton(btnCopy) from Form1, text should be copied same as when I Press PasteButton(btnPaste) from Form1, text that has been copied should be Paste in RichTextBox(rtb) that could be Found on Form2 .

How can I do that?

4

4 回答 4

1

假设您拥有Form1ToolStrip Button命名PasteToolStripButton为:

  public partial class Form1 : Form
{
    Form2 formChild;

    public Form1()
    {
        InitializeComponent();
        this.Load += new EventHandler(Form1_Load);
    }

    void Form1_Load(object sender, EventArgs e)
    {
       formChild = new Form2();
       formChild.MdiParent = this;
       formChild.Show();            
    }


   private void CopyToolStripButton_Click(object sender, EventArgs e)
    {
        formChild.CopyText(); // Method to copy Rich Text Box in Form2
    }

    private void PasteToolStripButton_Click(object sender, EventArgs e)
    {
        formChild.PasteText(); // Method in Form2 to Paste to the RichTextBox in Form2
    }

}

在你的Form2你需要添加一个Public名为PasteTextCopyText喜欢的方法:

  public void PasteText()
  {
     rtbChild.Text = Clipboard.GetText(); // this one simulates the rtb.Paste()
  }

  public void CopyText()
  {
     rtb.Copy(); 
  }

我还将RichTextBoxin命名Form2为,rtbChild因此每次单击时,例如 paste in 都会复制到您的RichTextBoxin 中Form2

于 2013-06-10T04:37:21.363 回答
0

在 Form1 上创建一个公共属性,然后从 Form2 设置它。编辑:在 Form1:公共字符串 TextForRTB {get; 放;}

在 Form2 上:Form1 a = new Form1(); a.TextForRtb = rtb.Text;

于 2013-06-10T04:29:14.083 回答
0

Sol1:将一种形式传递给另一种形式,就像Form1(Form parent){....}在构造函数中一样,那么您应该会看到它的公共属性和方法。

Sol2:创建自定义事件以在富文本框上的文本更改时引发它,因此使用此富文本框初始化表单的表单将执行某些操作,例如启用/禁用按钮或其他内容

...实际上,这种行为有很多解决方案,我想知道为什么您需要将文本框与在业务逻辑中似乎密切相关的按钮放在不同的形式!

于 2013-06-10T04:35:39.737 回答
0

您可以公开 2 种方法GetRichTextBoxContentSetRichTextBoxContentForm2. 这将更新richTextBoxin的内容Form2

然后你可以Instance处理Form2表单Form1

注意:这里的主要想法是您如何Instance获得Form2. 获取该实例取决于您的实现。

public class Form2 : Form
{
    public string GetRichTextBoxContent()
    {
        return this.richTextBox1.Text;
    }

    public void SetRichTextBoxContent(string content)
    {
        this.richTextBox1.Text = content;
    } 
}

public class Form1 : Form
{
    //Based on your implementation 
    Form2 form2 = new Form2();

    private void Button_CopyClick(object sender, EventArgs e)
    {
        var contentFromRtb = form2.GetRichTextBoxContent();
    } 
    private void Button_PasteClick(object sender, EventArgs e)
    {
        var someContent = "Content to be copied to text box"
        form2.SetRichTextBoxContent(someContent );
    } 
}
于 2013-06-10T04:35:56.857 回答