2011-01-13 62 views
1

我有一個問題,當我的主窗體在打開一個新表單時失去了焦點。我知道我可以通過使用mainForm.focus()來恢復焦點,但是如果我希望主窗體在新窗口打開時永不放棄焦點,我該如何處理這些事情呢?當我顯示另一個表單時,如何防止原始表單失去焦點?

+1

可能重複的[顯示窗體沒有偷焦點(在C#)] (http://stackoverflow.com/questions/156046/show-a-form-without-stealing-focus-in-c) – 2011-01-13 10:40:29

+1

[Show a Form without stealing focus?](http://stackoverflow.com中文/ questions/156046/show-a-form-without-stealing-focus) – 2017-05-17 14:58:41

回答

1

科迪格雷回答了這個問題,我只是通過直接粘貼代碼來擴展它。具有修改權可以複製它在那裏,並刪除這我都不在乎;)

pinvoke.net的ShowWindow方法:

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

您可以通過覆蓋屬性ShowWithoutActivation來完成此操作,以便以您希望顯示的形式返回true,而不必從顯示它的表單中偷取焦點,在您的情況下這將是您的主要形式。

相關問題