我有两种形式。主窗体包含treeview
。在我显示第二个表单后,树视图失去了焦点。没关系,但我希望在第二个表格关闭时激活树视图。
Form1.cs的
namespace ex
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (Form2 form2 = new Form2(this))
{
form2.StartPosition = FormStartPosition.CenterParent;
form2.ShowDialog();
}
}
internal void example()
{
treeView1.SelectedNode = treeView1.Nodes[1];
}
private void Form1_Load(object sender, EventArgs e)
{
TreeNode node = new TreeNode("aaaa");
treeView1.Nodes.Add(node);
node = new TreeNode("bbbb");
treeView1.Nodes.Add(node);
node = new TreeNode("cccc");
treeView1.Nodes.Add(node);
}
}
}
Form2.cs
namespace ex
{
public partial class Form2 : Form
{
Form1 form1;
public Form2(Form1 form1)
{
InitializeComponent();
this.form1 = form1;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
form1.example();
//not working
form1.treeView1.Focus();
form1.treeView1.Select();
}
}
}
答案 0 :(得分:0)
Form2真的不应该与Form1如此亲密。尝试像这样转动你的代码:
private void button1_Click(object sender, EventArgs e)
{
using (Form2 form2 = new Form2(this))
{
if (form2.ShowDialog(this) == DialogResult.OK) {
treeView1.Select();
example();
}
}
}
如果Form2应该提供要添加到TreeView控件的任何信息,那么您将在Form2上设置一个属性并从同一代码块中访问它。