猪头少年 - 云南AI专家 - 云南独立开发者
全部文章

Engineering note

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);

继续阅读

从文章索引继续。

这篇文章暂未归入核心专题;你仍可从全部文章中找到下一篇相关内容。

选择一条专题路线

Keep reading

相关文章

2026 最新 Windows 桌面应用发布免费代码签名指南:上架 Microsoft Store,使用 MSIX 分发继续阅读 我为什么做 Winsaa继续阅读 计划、执行与反思:把多步任务变成可恢复过程继续阅读 知识库与检索增强:先让答案可追溯继续阅读

Next step

不要停在单篇文章。

沿主专题继续阅读,查看同一问题从概念到实战的完整路径。

选择一条专题路线