在沒有靜態和新類()的情況下調整Form大小時如何呼叫Form 1的方法;像下面的代碼。因為不止一個 new class(); 使用代碼時會導致“System.StackOverflowException”問題。由于靜態,它不會采用它保存在類中的值。
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);
}
uj5u.com熱心網友回復:
可以訂閱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.
uj5u.com熱心網友回復:
另一個,通過Show()自身傳遞 Form1:
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 中,您.Owner轉換回 Form1:
private void Form2_Resize(object sender, EventArgs e)
{
Form1 f1 = (Form1)this.Owner;
f1.ResizePicture(this.Height, this.Width);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/437729.html
