如何在没有静态和新类()的情况下从 Form2 调用表单 1 的方法;



如何在没有静态和新类((的情况下调整Form的大小时调用Form 1的方法;就像下面的代码一样。因为有多个新类((;";System.StackOverflowException";使用代码时会出现问题。它不接受保存在类中的值due-static。

Form1类代码:

Form2 frm2 = new Form2();
public void ResizePicture(int Height, int Width)
{
frm2.pictureBox1.Height = Height;
frm2.pictureBox1.Width = Width;
}
private void button1_Click(object sender, EventArgs e)
{
frm2.pictureBox1.Image = Image.FromFile(@"C:UsersOmerDesktopscreenshot.png");
frm2.Show();
}

Form2类代码:

private void Form2_Resize(object sender, EventArgs e)
{
ResizePicture(this.Height, this.Width);
}

您可以订阅其他形式的Resize事件

形式1:

private readonly Form2 frm2;
private Form1()
{
InitializeComponent();
frm2 = new Form2();
frm2.Resize += Frm2_Resize;
}
private void Frm2_Resize(object sender, EventArgs e)
{
...
}

此代码只在Form1的构造函数中创建一次Form2。现在Form2的Resize事件处理程序在Form1中。


另一种可能性是将第一种形式的引用传递给第二种形式的

形式2:

private readonly Form1 frm1;
private Form2(Form1 frm1)
{
InitializeComponent();
this.frm1 = frm1;
}
private void Form2_Resize(object sender, EventArgs e)
{
frm1.ResizePicture(this.Height, this.Width);
// Note: `ResizePicture` must be public but not static!
}

形式1

frm2 = new Form2(this); // Pass a reference of Form1 to Form2.

另一个,通过Show()本身传递Form1:

private void button1_Click(object sender, EventArgs e)
{
frm2.pictureBox1.Image = Image.FromFile(@"C:UsersOmerDesktopscreenshot.png");
frm2.Show(this); // <-- passing Form1 here!
}

在Form2中,您将.Owner转换回Form1:

private void Form2_Resize(object sender, EventArgs e)
{
Form1 f1 = (Form1)this.Owner;
f1.ResizePicture(this.Height, this.Width);
}

相关内容

最新更新