abramlimpin
abramlimpin

Reputation: 5077

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

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?

Upvotes: 0

Views: 2386

Answers (5)

Richard Vera
Richard Vera

Reputation: 1

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

Upvotes: 0

The King
The King

Reputation: 4650

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

Upvotes: 0

Rowland Shaw
Rowland Shaw

Reputation: 38130

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

Upvotes: 0

Ben
Ben

Reputation: 3912

Have you tried

txtSearch.Select ()
txtSearch.Focus()

?
Is your TextBox within a GroupBox?

Upvotes: 0

TheGeekYouNeed
TheGeekYouNeed

Reputation: 7539

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

Upvotes: 4

Related Questions