如另一个响应中所述,实现此目的的一种方法(当然是unelegant)是使用user32.dll并调用本机方法,如果我们使用一些来自窗口调用方的未链接进程或线程,这可能是有效的,这些进程或线程在主调用方中设置为后台窗口(例如:对于我们想要最顶层的窗口,始终位于顶部)。
这是部分复制的,但只是为了方便:
public enum WindowPos : int
{
HWND_NOTOPMOST=-2,
HWND_TOPMOST=-1,
HWND_TOP=0,
HWND_BOTTOM=1
}
public enum WindowFlags : uint
{
SWP_NOSIZE=0x0001,
SWP_NOMOVE=0x0002,
SWP_NOZORDER=0x0004,
SWP_NOREDRAW=0x0008,
SWP_NOACTIVATE=0x0010,
SWP_FRAMECHANGED=0x0020, /* The frame changed: send WM_NCCALCSIZE */
SWP_SHOWWINDOW=0x0040,
SWP_HIDEWINDOW=0x0080,
SWP_NOCOPYBITS=0x0100,
SWP_NOOWNERZORDER=0x0200, /* Don't do owner Z ordering */
SWP_NOSENDCHANGING=0x0400 /* Don't send WM_WINDOWPOSCHANGING */
}
public enum ShowWindowCommands : int
{
SW_HIDE=0,
SW_SHOWNORMAL=1,
SW_NORMAL=1,
SW_SHOWMINIMIZED=2,
SW_SHOWMAXIMIZED=3,
SW_MAXIMIZE=3,
SW_SHOWNOACTIVATE=4,
SW_SHOW=5,
SW_MINIMIZE=6,
SW_SHOWMINNOACTIVE=7,
SW_SHOWNA=8,
SW_RESTORE=9,
SW_SHOWDEFAULT=10,
SW_FORCEMINIMIZE=11,
SW_MAX=11
}
private static class User32
{
[DllImport("user32.dll")]
internal static unsafe extern IntPtr SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
internal static unsafe extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
internal static unsafe extern bool SetWindowPos(IntPtr hWnd, int hWndPutAfter, int x, int y, int cx, int cy, uint flags);
[DllImport("user32.dll")]
internal static unsafe extern IntPtr SetFocus( IntPtr hWnd );
}
public void Activate()
{
Process currentProcess = Process.GetCurrentProcess();
IntPtr hWnd = currentProcess.MainWindowHandle;
if (hWnd != IntPtr.Zero)
{
User32.SetWindowPos(hWnd, (int)WindowPos.Top, 0, 0, 0, 0, (uint)(WindowFlags.SWP_NOMOVE | WindowFlags.SWP_NOSIZE));
User32.ShowWindow(hWnd, (int)ShowWindowCommands.SW_SHOW);
User32.SetForegroundWindow(hWnd);
User32.SetFocus( hWnd );
}
}
为了完整起见,我添加了Windows SDK中可用常量的大多数引用