问题
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