新建一个 WinForm项目,在项目的.cs文件中加入以下代码:
1、引入命名空间:
using System.Runtime.InteropServices;
2、在窗口类中加入:
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hPos,
int x, int y, int cx, int cy, uint nflags);
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hPos,
int x, int y, int cx, int cy, uint nflags);
3、在窗口的Load事件中加入:
置顶
IntPtr HWND_TOPMOST = new IntPtr(-1);
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, 0x0001 | 0x0002);
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, 0x0001 | 0x0002);
取消置顶
IntPtr HWND_TOPMOST = new IntPtr(-2);
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, 0x0001 | 0x0002);
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, 0x0001 | 0x0002);