使用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`函数。

相关推荐
Imagine Miracle6 小时前
【WSL】让WSL2后台持久运行不自动关闭的解决方案
linux·windows·wsl
啦啦啦~~~2226 小时前
经典小游X,免费刺激,可离线使用!
windows·游戏·开源软件
逆向编程6 小时前
Socket异常连接自动清理方案
开发语言
va学弟7 小时前
Java 网络通信编程(10):Channel 和 Selector
java·开发语言
爱吃提升7 小时前
MATLAB impulse函数脉冲响应完整实操教程
开发语言·matlab
小饕8 小时前
从 1080 Ti 到树莓派 4:Qwen2.5-0.5B Function Calling 端侧部署七步实战
开发语言·人工智能
月走乂山8 小时前
Windows提示调制解调器报错、同交换机其他电脑正常、远程能连但浏览器打不开——本机DNS配置问题排查
windows·dns·故障排查·网络故障·网络诊断
糯米导航8 小时前
Rust + ONNX Runtime 构建生产级 AI 推理服务:从零到压测
开发语言·人工智能·rust
阿pin8 小时前
Java随笔-ConcurrentHashMap
java·开发语言·哈希算法
秋田君8 小时前
QT_QT布局详解
开发语言·数据库·qt