C#/ .NET:启动进程后,TextBox不会“聚焦”

单击“btnSearch”按钮后打开记事本后出现问题。

我的想法是,一旦我点击“btnSearch”按钮,即使在主窗口外启动/打开进程后,文本框“txtSearch”也应该“聚焦”。

这是我的代码:

private void btnSearch_Click(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start("notepad"); txtSearch.Focus(); // not working } 

有什么建议?

以下是您需要的代码。 这可以通过互操作服务来完成

  private void setwind() { System.Diagnostics.Process.Start("notepad"); System.Threading.Thread.Sleep(2000); // To give time for the notepad to open if (GetForegroundWindow() != this.Handle) { SetForegroundWindow(this.Handle); } } [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); 

在你的Page_Load事件中尝试

 Control c= GetPostBackControl(this.Page); if(c != null) { if (c.Id == "btnSearch") { SetFocus(txtSearch); } } 

然后将其添加到您的页面或BasePage或其他任何内容

 public static Control GetPostBackControl(Page page) { Control control = null; string ctrlname = page.Request.Params.Get("__EVENTTARGET"); if (ctrlname != null && ctrlname != String.Empty) { control = page.FindControl(ctrlname); } else { foreach (string ctl in page.Request.Form) { Control c = page.FindControl(ctl); if(c is System.Web.UI.WebControls.Button) { control = c; break; } } } return control; } 

你有没有尝试过

 txtSearch.Select () txtSearch.Focus() 


你的TextBox在GroupBox中吗?

应用程序无法从其他应用程序“窃取”焦点(自Windows XP以来),它们可以实现的最接近的是闪烁任务栏,这可以通过P / Invoke实现:

 [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool FlashWindow(IntPtr handle, bool invert); 

然后传递表格的Handle

查看TabIndex属性。 在启动应用程序时需要关注的控件上使用值0。