这是示例代码
Form 1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FormBorderStyle = FormBorderStyle.None;
}
private void btnAdmin_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.Show();
}
}
表格1打开表格2,询问管理员密码。
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text == "123")
{
Setting frm = new Setting();
frm.Show();
this.Close();
}
else
{
MessageBox.Show("You have entered wrong password.");
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
现在,如果您输入了正确的密码,它将进入表格3,这是表格1的设置菜单。
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
frm.Show();
if (fullscreenYes.Checked == true)
{
frm.FormBorderStyle = FormBorderStyle.None;
}
if (fullscreenYes.Checked == false)
{
frm.FormBorderStyle = FormBorderStyle.FixedSingle;
}
this.Close();
}
}
所以现在,我想使用单选按钮从表单3更改表单1的FormBorderStyle,但是它不起作用,因为我当前的代码只是打开一个新Form1并将该设置应用于新打开的Form 1并保留先前打开的Form 1开了 我最终像这样打开了2个表格1。如何在不打开2个表单1的情况下直接从表单3更改表单1的属性?我已经在这里待了几个小时了,但无法弄清楚。帮助。
答案 0 :(得分:1)
有几种方法可以实现您的目标。
#1允许通过其构造函数访问Form1来访问Form3
private Form1 _owner;
public Form3(Form1 owner)
{
owner = _owner;
}
void DoSomethingToForm1()
{
// do something.. _owner.Prop = ?;
}
然后从Form1调用Form3
new Form3(this).Show();
#2使用单例模式
private static object _lockObj = new object();
private static Form1 _instance = new Form1();
public static Form1 Instance
{
lock(_lockObj)
{
get
{
if(_instance == null || _instance.IsDisposed) _instance = new Form1();
return _instance;
}
}
}
然后从Form3调用Form1
var f = Form1.Instance;
// do something to form1
答案 1 :(得分:0)
要处理现有的表单实例,以便您可以修改或设置内容,请使用OpenForms.OfType
快速样本:
var frm1 = Application.OpenForms.OfType<Form1>().Single();
//set some stuff
frm1.FormBorderStyle = FormBorderStyle.None;
frm1.Show();