How to press a button from another form using C#?

后端 未结 2 1313
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 16:10

I have 2 forms:

  1. Form1 that make a screenshot.
  2. Form2 that have 2 buttons to manipulate the screenshot created by form1.

Form1 also have

相关标签:
2条回答
  • 2021-01-14 16:17

    First of all the normal way multiple forms work is that when you close down the Startup form then the secondary forms will close also. If you are creating your Form2 in Form1 I would show it by using (your second Forms Instance).Show(this). You could then access the Form by Form2's Parent Property. i.e.

          var form = (Form1)this.Owner();
    

    You should then be able to access all of the public methods of Form1, Also I would take the code that you are using to save your screenshot and put into a public method, no need to have it in a Button's click event especially if the button is hidden.

    Here is a quick example:

    Form1

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm = new Form2();
            frm.Show(this);
        }
    
    }
    

    Form2

    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            var frm = (Form1)this.Owner;
            if (frm != null)
                frm.button1.PerformClick();
        }
    }
    
    0 讨论(0)
  • 2021-01-14 16:20

    Instead of making a hidden button just make a method not linked to a button.

    In Form1.cs:

    public void SaveScreenshot()
    {
        //TODO: Save the Screenshot
    }
    

    In Form2.cs:

    Form1 form = Application.OpenForms.OfType<Form1>().FirstOrDefault();
    if (form != null) {
        form.SaveScreenshot();
    }
    

    Also make sure to declare the SaveScreenshot method as public or internal.

    I changed the code that gets Form1. If you click a button on Form2 then Form2 will be the ActiveForm, so your code will never "see" Form1. I used LINQ methods in my code that will only work if you have a using System.Linq; at the top of your code.

    0 讨论(0)
提交回复
热议问题