0

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

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

这是我的代码:

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

有什么建议么?

4

5 回答 5

4

在您的 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;
}
于 2010-04-01T07:46:45.303 回答
0

你有没有尝试过

txtSearch.Select ()
txtSearch.Focus()

?
您的 TextBox 在 GroupBox 内吗?

于 2010-04-01T10:41:14.160 回答
0

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

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

然后通过它的形式Handle

于 2010-04-01T15:14:55.677 回答
0

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

    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();
于 2010-06-11T13:50:35.833 回答
0

TabIndex楼盘。启动应用程序时,在需要聚焦的控件上使用值 0。

于 2012-08-08T17:07:44.887 回答