views:

310

answers:

4

Hi,

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  A: 

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;
}
TheGeekYouNeed
Is the 'Control' under System.Windows.Forms.Control or System.Windows.Controls.Control ?
eibhrum
This answer appears to be referring to ASP.Net, rather than WinForms (or WPF)
Rowland Shaw
Yes, sorry, this is an ASP.Net example.
TheGeekYouNeed
He didn't specify WinForms exactly, and the sample if pertinent and a simlar methodolgy could be used on a WinForm; I don't know why this is down voted. *shrug*
TheGeekYouNeed
A: 

Have you tried

txtSearch.Select ()
txtSearch.Focus()

?
Is your TextBox within a GroupBox?

Ben
txt.Search.Select is not working too. I just want to 'focus' the textbox (the bar should be blinking)
eibhrum
the textbox is not within a groupbox
eibhrum
A: 

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

Rowland Shaw
A: 

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