如何在没有静态和新 class()的情况下从 Form2 调用 Form 1 的方法;?

How to call Form 1's method from Form2 without static and new class();?

提问人:ÖMER 提问时间:3/2/2022 最后编辑:Olivier Jacot-DescombesÖMER 更新时间:3/2/2022 访问量:304

问:

在没有 static 和 new class() 的情况下调整 Form 的大小时如何调用 Form 1 的方法;就像下面的代码一样。因为有多个新 class();使用代码时导致的“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:\Users\Omer\Desktop\screenshot.png");
    frm2.Show();
}

Form2 类代码:

private void Form2_Resize(object sender, EventArgs e)
{
    ResizePicture(this.Height, this.Width);
}
C# 图像 方法 调整大小 调用

评论


答:

1赞 Olivier Jacot-Descombes 3/2/2022 #1

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

在 Form1 中:

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 中。


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

在 Form2 中:

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.
0赞 Idle_Mind 3/2/2022 #2

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

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

在 Form2 中,转换回 Form1:.Owner

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

评论

0赞 Olivier Jacot-Descombes 3/2/2022
这是个好主意;但是,它的副作用是 Form2 将始终显示在 Form1 之上。请参见:Form.Owner 属性备注
1赞 Idle_Mind 3/2/2022
真!它们被“链接”在一起。最小化/还原 Form1 将使 Form2 跟随它。我最喜欢你的活动方式 @OlivierJacot-Descombes。只是展示了另一种选择。这个需要最少的代码更改,但不如你的两个示例强大。