我一直在尝试用自己的选项窗口编写一个小应用程序.当我尝试启动窗口时,我似乎无法将注意力集中在新窗体上.这不是mdi表单,而只是我在用户从菜单中选择选项时创建的新表单.应该注意的是,Form.Show返回false,这意味着新表单永远不会获得焦点.
我尝试了多种加载表单的方法,但都失败了:
来自电话表格:
ServerForm SF = new ServerForm(ref DataLoader, false);
SF.Show();
SF.Focus();
// Fails
Run Code Online (Sandbox Code Playgroud)
在表单内部:
this.Show();
this.BringToFront();
this.Activate();
this.TopMost = true;
// Fails
Run Code Online (Sandbox Code Playgroud)
将表单设置为可选:
this.SetStyle(System.Windows.Forms.ControlStyles.Selectable, true);
...
ServerForm SF = new ServerForm(ref DataLoader, false);
SF.Show();
SF.Focus();
// Fails
Run Code Online (Sandbox Code Playgroud)
使用旧API:
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int ShowWindow(IntPtr handle, int nCmdShow);
ServerForm SF = new ServerForm(ref DataLoader, false);
ShowWindow(SF.Handle, 3);
SF.Show();
SF.Focus();
// Fails
Run Code Online (Sandbox Code Playgroud)
传递父母
ServerForm SF = new ServerForm(ref DataLoader, false);
SF.Show(this);
SF.Focus();
// Fails
Run Code Online (Sandbox Code Playgroud)
在所有这些情况下,表单都会显示,但生成的表单仍然会关注新表单.即使我在创建新表单之前禁用旧表单,也会发生这种情况.
有什么建议?
小智 11
这是因为Form.canFocus()表单加载时为false.使用Form.Activate()上的Form.Shown事件.就这样.
private void ServerForm_Shown(object sender, EventArgs e)
{
this.Activate();
}
Run Code Online (Sandbox Code Playgroud)