在论坛中看到有人问如何可以让任意Windows窗口置顶,这里其实可以使用Windows API函数SetWindowsPos做到。以下是示例代码:

示例代码演示将一个新打开的记事本程序置顶

 1 [DllImport(user32.dll, SetLastError = true)]
 2 public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
 3 
 4 [DllImport(user32.dll)]
 5 public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
 6 
 7 public static readonly IntPtr HWND_TOPMOST = new IntPtr(1);    //窗体置顶
 8 public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(2);    //取消窗体置顶
 9 public const uint SWP_NOMOVE = 0x0002;    //不调整窗体位置
10 public const uint SWP_NOSIZE = 0x0001;    //不调整窗体大小
11 
12 private void button1_Click(object sender, EventArgs e)
13 {
14     //找到默认的打开的记事本程序
15     IntPtr notepadHandle = FindWindow(null无标题 – 记事本);
16     if (notepadHandle == null || notepadHandle == IntPtr.Zero)
17         return;
18     SetWindowPos(notepadHandle, HWND_TOPMOST, 1111, SWP_NOMOVE | SWP_NOSIZE);
19 }


理解的越多,需要记忆的就越少