如何从form1更改form2的位置 [英] How to change location of form2 from form1
问题描述
Form1和form2在程序启动时运行。在form1上我有pictureBox1,我想在用户点击pictureBox1时改变form2的位置(在屏幕的中心)。如何正确引用两个表格?
我尝试过:
form2已经在屏幕外的位置运行(故意),当用户点击pictureBox1(在form1上)时,我需要它返回屏幕的中心
取决于如何创建这两个表单。
因为你已经将它们称为form1和form2,所以你可能在form1代码中创建了form2实例,并使用form2.Show来显示它。 br />
在这种情况下它非常简单:使用你创建的form2实例,在form1中的类级别变量中进行操作:
private Form2 form2 = null ;
...
form2 = new Form2();
form2.Show();
...然后,在你的PictureBox.Click事件处理程序中:
void myPictureBox_Click( object sender,EventArgs e)
{
Rectangle screen = Screen.PrimaryScreen.WorkingArea;
form2.Location = new Point((screen.Width - form2.Width)/ 2 ,(screen.Height - form2.Height)/ 2 );
}
拼写错误[/ edit]
< blockquote>请参阅我专门撰写的文章来回答所有类似的问题:很多问题一次回答 - Windows窗体或WPF Windows之间的协作 [ ^ ]。
>
Form1 and form2 a running when program start. On form1 i have pictureBox1 and i want to change location of form2 (on center of the screen) when user click on pictureBox1. How to reference two form correctly?
What I have tried:
form2 is already running in location outside of screen (deliberately) and i need it to return on centar of screen when user click pictureBox1(on form1)
Depends on how you create the two forms.
Since you have called them "form1" and "form2" the chances are that you created the form2 instance in form1 code, and used form2.Show to display it.
In which case it's pretty simple: use the instance of form2 that you created, by stroring it in a class level variable in form1:
private Form2 form2 = null; ... form2 = new Form2(); form2.Show(); ...Then, in your PictureBox.Click event handler:
void myPictureBox_Click(object sender, EventArgs e) { Rectangle screen = Screen.PrimaryScreen.WorkingArea; form2.Location = new Point((screen.Width - form2.Width) / 2, (screen.Height - form2.Height) / 2); }
[edit]Spelling mistake[/edit]
Please see my article written specially to answer all similar questions: Many Questions Answered at Once — Collaboration between Windows Forms or WPF Windows[^].
—SA
这篇关于如何从form1更改form2的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!