简体   繁体   English

C# 从另一个表单执行原始表单中的方法

[英]C# Excecute method in original Form from another Form

I have a simple question for some of you.我有一个简单的问题要问你们中的一些人。

I have two forms which contain two methods:我有两个 forms,其中包含两种方法:

FORM 2: Which will take input from textbox and run a method from FORM1 FORM 2:将从textbox获取输入并运行FORM1中的方法

public partial class Form2 : Form
    {
        Form1 mainForm = new Form1();
        public Form2()
        {
            InitializeComponent();
            //Form2_Load();
                        
        }


        private void txtCmdOutput_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    mainForm.outPutMessage(txtCmdOutput.Text.Length, 2, txtCmdOutput.Text.ToString());
                    txtCmdOutput.Text = "";

                }
            }
            catch (Exception err)
            {

            }
        }

FORM 1: Which will contain the method that will excecute using the inputs from FORM 2 FORM 1:它将包含将使用FORM 2的输入执行的方法

public void outPutMessage(int bufferSize1, int messageID1, string message1)
        {
            NetworkStream networkstream = client.GetStream();


            int bufferSize = bufferSize1;
            var message = message1;

            int messageID = messageID1;

            string headerStr = "len:" + message.Length.ToString() + "\r\nMsgId:" + messageID;

            byte[] headerLength = BitConverter.GetBytes(headerStr.Length);

            networkstream.Write(headerLength, 0, 4);

            networkstream.Write(Encoding.ASCII.GetBytes(headerStr), 0, headerStr.Length);


            int bytesSent = 0;
            int bytesLeft = message.Length;
            byte[] encodedMessage = Encoding.ASCII.GetBytes(message);

            while (bytesLeft > 0)
            {
                int curDataSize = Math.Min(bufferSize, bytesLeft);
                networkstream.Write(encodedMessage, bytesSent, curDataSize);

                bytesSent += curDataSize;
                bytesLeft -= curDataSize;
            }
        }

My question is, is it possible to call the我的问题是,是否可以调用

outPutMessage(txtCmdOutput.Text.Length, 2, txtCmdOutput.Text.ToString());

from FORM 2 (by taking the input from the textbox ), but actually run the method in its original form ( FORM 1 )?来自FORM 2 (通过从textbox获取输入),但实际上以其原始形式( FORM 1 )运行该方法? as there is where all the other variables are contained.因为那里包含所有其他变量。

What I attempted to do is indicate Form1 mainForm = new Form1();我试图做的是指示Form1 mainForm = new Form1(); and call the method, but it seems to then run the method in FORM 2 .并调用该方法,但它似乎随后在FORM 2中运行该方法。

UPDATE:更新:

This is how I create FORM 2 from FORM 1 :这就是我从FORM 1创建FORM 2的方式:

private void button_Click1(object sender, EventArgs e)
        {
            Button selected = sender as Button;
            openClientForm(new Form2());
            outPutMessage("".Length, 4, ""); 
        }

private Form2 activeForm = null;
        private void openClientForm(Form2 clientForm)
        {
            if (activeForm != null)
                activeForm.Close();
            activeForm = clientForm;
            clientForm.TopLevel = false;
            clientForm.FormBorderStyle = FormBorderStyle.None;
            clientForm.Dock = DockStyle.Fill;
            panelClientForm.Controls.Add(clientForm);
            panelClientForm.Tag = clientForm;
            clientForm.BringToFront();
            clientForm.Show();
        }

THanks in advance.提前致谢。

As per @jmcilhinney setup an event in the child form, here in a Button Click event push information to listeners which means the child form does not know anything about the calling form.根据@jmcilhinney 在子表单中设置一个事件,这里在 Button Click 事件中将信息推送给侦听器,这意味着子表单对调用表单一无所知。

This would be your child form这将是你的孩子形式

namespace PassStringFromChildToParentForm
{
    public partial class ChildForm : Form
    {
        public delegate void OnPassData(int bufferSize1, int messageID1, string message1);
        public event OnPassData PassData;

        public ChildForm()
        {
            InitializeComponent();
        }

        private void PassDataButton_Click(object sender, EventArgs e)
        {
            PassData?.Invoke(textBox1.Text.Length,2, textBox2.Text);
        }
    }
}

The main form主要形式

namespace PassStringFromChildToParentForm
{
    public partial class MainForm : Form
    {

        public MainForm()
        {
            InitializeComponent();
        }

        private void ShowChildForm_Click(object sender, EventArgs e)
        {
            ChildForm childForm = new ChildForm();
            childForm.PassData += PassData;
            childForm.Show(this);
            
        }
        private void PassData(int bufferSize1, int messageID1, string message1)
        {
            // perform work
        }
    }
}

This may help you.这可能对你有帮助。 If you change your Program.cs file to save your mainForm as a public variable like this:如果您更改Program.cs文件以将mainForm保存为公共变量,如下所示:

static class Program
{
    public static Form1 mainForm;

    [STAThread]
    static void Main()
    {

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(mainForm = new Form1());
    }
}

Then when you need to reference the mainForm in your appliation like from Form2 or anywhere else you can use the following:然后,当您需要在您的应用程序中引用mainForm时,例如从 Form2 或其他任何地方,您可以使用以下内容:

Program.mainForm.outPutMessage();

This will allow you to access anything from the mainForm as long as its public.这将允许您从 mainForm 访问任何内容,只要它是公开的。

Or another approach is to pass a reference of Form1 to Form2 when you create it so that you can reference it later as I suggested in comments.或者另一种方法是在创建时将 Form1 的引用传递给 Form2,以便稍后可以按照我在评论中的建议引用它。

private void button_Click1(object sender, EventArgs e)
{
    Button selected = sender as Button;
    // if run from Form1 then 'this' is form1
    openClientForm(new Form2(this)); 
    outPutMessage("".Length, 4, ""); 
}

Then change Form2.cs constructor to save it:然后更改 Form2.cs 构造函数以保存它:

public partial class Form2 : Form
{
    private Form1 mainForm;
    public Form2(Form1 mForm)
    {
        InitializeComponent();
        this.mainForm = mForm;          
    }

Then from that point on you can just use:然后从那时起你可以使用:

mainForm.outPutMessage();

The problem with this approach is that anytime you create a Form2 you need to pass it Form1.这种方法的问题在于,无论何时创建 Form2,都需要将其传递给 Form1。 Or you can pass it another form, or null, but that may cause issues depending on your code.或者您可以向它传递另一种形式,或 null,但这可能会导致问题,具体取决于您的代码。

There are many other solutions for what you are trying to accomplish, but I believe these are likely what you are looking for in your current scenerio without refactoring everything.对于您要实现的目标,还有许多其他解决方案,但我相信这些可能是您在当前场景中寻找的,而无需重构所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM