C#/.NET: TextBox is not 'focused' after a process was initiated

倖福魔咒の 提交于 2020-01-24 00:44:30

问题


I am having a problem after opening the notepad once I click the button "btnSearch".

The idea is that once I clicked the button 'btnSearch', the textbox 'txtSearch' should be 'focused' even after a process was initiated/opened outside the main window.

Here's my code:

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

Any suggestions?


回答1:


The below is the code you would need. This could be done through interop services

    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();



回答2:


In your Page_Load event try

Control c= GetPostBackControl(this.Page);

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

}

Then add this to your page or BasePage or whatever

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;
}



回答3:


Have you tried

txtSearch.Select ()
txtSearch.Focus()

?
Is your TextBox within a GroupBox?




回答4:


Applications cannot "steal" focus from other applications (since Windows XP), the closest they can achieve is flashing the taskbar, which is possible via P/Invoke:

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

Then pass it the form's Handle




回答5:


Look at the TabIndex property. Use a value of 0 on the control you need focused when you start the application.



来源:https://stackoverflow.com/questions/2558809/c-net-textbox-is-not-focused-after-a-process-was-initiated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!