在論壇中看到有人問如何可以讓任意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, 1, 1, 1, 1, SWP_NOMOVE | SWP_NOSIZE);
19 }