C#桌面应用置顶

Winform和WPF开发中,有时会有需要置顶窗体的需求,本文就介绍怎么使用Win32API进行置顶

C#加载Win32API

/// <summary> 
/// 设置当前窗体位置
/// </summary> 
/// <returns></returns> 
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int Width, int Height, int flags);

/// <summary> 
/// 得到当前活动的窗口 
/// </summary> 
/// <returns></returns> 
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern System.IntPtr GetForegroundWindow();

调用方法

Winform调用

Winform 中对于窗体和控件都有一个 Intptr 类型的属性 Handle,该属性指向了自身指针,可直接用于调用

SetWindowPos(this.Handle, -1, 0, 0, 0, 0, 1 | 2); //最后参数也有用1 | 4

WPF调用

WPF 中,没有直接的 Handle 属性供给调用,需要使用 WindowInteropHelper 来获得窗体的引用,在进行置顶

SetWindowPos(new WindowInteropHelper(this).Handle, -1, 0, 0, 0, 0, 1 | 2);
发布时间:2021-10-10