问题
I am having a problem where my main form loses focus when opening a new form. I know I can revert the focus back by using mainForm.focus()
, but how do I handle things if I want the main form to never give up its focus when new window is opened?
回答1:
You can accomplish this by overriding the property ShowWithoutActivation in order for it to return true
in the forms that you want to show without stealing focus from the form that shown it, in your case that would be your main form.
回答2:
Cody Gray answered this, I'm just expanding it by directly pasting the code. Someone with edit rights can copy it over there and delete this for all I care ;)
pinvoke.net's ShowWindow method.:
private const int SW_SHOWNOACTIVATE = 4;
private const int HWND_TOPMOST = -1;
private const uint SWP_NOACTIVATE = 0x0010;
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
static extern bool SetWindowPos(
int hWnd, // window handle
int hWndInsertAfter, // placement-order handle
int X, // horizontal position
int Y, // vertical position
int cx, // width
int cy, // height
uint uFlags); // window positioning flags
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
static void ShowInactiveTopmost(Form frm)
{
ShowWindow(frm.Handle, SW_SHOWNOACTIVATE);
SetWindowPos(frm.Handle.ToInt32(), HWND_TOPMOST,frm.Left, frm.Top, frm.Width, frm.Height,SWP_NOACTIVATE);
frm.TopMost = false;
}
来源:https://stackoverflow.com/questions/4679013/how-do-i-prevent-the-original-form-from-losing-focus-when-i-show-another-form