使用C#根据Windows API判断窗体是否置顶

要使用C#根据Windows API判断窗体是否置顶,您可以使用以下代码示例。这个示例使用了Windows API函数来获取窗体的扩展样式,并检查是否设置了"WS_EX_TOPMOST"标志,以确定窗体是否置顶。

```csharp

using System;

using System.Diagnostics;

using System.Runtime.InteropServices;

class Program

{

// 导入Windows API函数

DllImport("user32.dll")

public static extern IntPtr GetForegroundWindow();

DllImport("user32.dll")

public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

const int GWL_EXSTYLE = -20;

const int WS_EX_TOPMOST = 0x00000008;

static void Main()

{

IntPtr foregroundWindow = GetForegroundWindow();

int exStyle = GetWindowLong(foregroundWindow, GWL_EXSTYLE);

bool isTopMost = (exStyle & WS_EX_TOPMOST) != 0;

if (isTopMost)

{

Console.WriteLine("当前窗口置顶。");

}

else

{

Console.WriteLine("当前窗口不置顶。");

}

}

}

```

此代码首先使用`GetForegroundWindow`函数获取当前活动窗口的句柄,然后使用`GetWindowLong`函数获取窗口的扩展样式。最后,它检查是否设置了`WS_EX_TOPMOST`标志,如果设置了,就表示窗口处于置顶状态。

请注意,这段代码只能检查当前活动窗口是否置顶。如果您想检查其他窗口的置顶状态,需要传递相应窗口的句柄给`GetWindowLong`函数。

相关推荐
村口曹大爷8 分钟前
JDK 24 正式发布:性能压轴,为下一代 LTS 铺平道路
java·开发语言
Web极客码19 分钟前
使用VPS主机进行数据分析的主要优势
linux·windows·vps主机
ysdysyn1 小时前
C# Modbus RTU 多从站控制全攻略:一端口,双轴控制
开发语言·c#·mvvm·通讯·modbus rtu
hashiqimiya1 小时前
java程序的并发
java·开发语言·python
seasonsyy1 小时前
Win7/Win10系统显示文件扩展名方法
windows
微露清风1 小时前
系统性学习C++进阶-第十四讲-二叉搜索树
开发语言·c++·学习
董世昌411 小时前
强制类型转换和隐式类型转换的区别
开发语言
Fruiticecake1 小时前
Markdown,不用鼠标也能做笔记!
开发语言
TypingLearn1 小时前
2026年,让.NET再次伟大
windows·c#·.net·sdk·netcore
ulias2122 小时前
多态理论与实践
java·开发语言·前端·c++·算法