Skip to main content
 首页 » 编程设计

c#之为什么 Form 得不到焦点

2024年02月06日11wuhuacong

我有一个像这样模态启动的表单:

private void find_street_Click(object sender, EventArgs e) 
{ 
  this.WindowState = FormWindowState.Minimized; 
  Form findForm = new FindStreet(); 
  findForm.ShowDialog(); 
  this.WindowState = FormWindowState.Normal; 
} 

表单正确启动,光标位于第一个文本框中,其 TabIndex 设置为 1。

随着 InitializeComponent(); 调用,这些命令也出现了。

public FindStreet() 
{ 
  InitializeComponent(); 
  this.TopMost = true; 
  this.BringToFront(); 
  this.Focus(); 
} 

我看过并尝试过一些例子。光标出现在正确的控件中,但窗体的窗口没有焦点。问题是,如果用户开始键入,即使新启动的表单可见,这些击键也不会进入文本框。

请您参考如下方法:

删除 public FindStreet() 中的代码,并在 FindStreet 的加载事件中添加:

this.TopMost = true; //i don't know why you need this. 
this.Activate(); 

当您最小化主窗体时,z 顺序中的下一个窗体将获得光标。 this.Focus() 什么都不做。您需要激活对话框。