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

相关推荐
2301_7657031415 分钟前
C++中的职责链模式实战
开发语言·c++·算法
面对疾风叭!哈撒给18 分钟前
Windows 系统使用NSSM创建 Windows服务
windows
f狐0狸x29 分钟前
【C++修炼之路】C++ list容器基本用法详解
开发语言·c++·list
坚持就完事了34 分钟前
Java的OOP
java·开发语言
jllllyuz38 分钟前
基于MATLAB的锂电池物理对象建模实现
开发语言·matlab
MyBFuture43 分钟前
C#数组详解:一维二维与交错数组
开发语言·windows·c#·visual studio·vision pro
生活很暖很治愈1 小时前
GUI自动化测试[3]——控件&数鼠标操作
windows·python·功能测试·测试工具
程序 代码狂人1 小时前
CentOS7初始化配置操作
linux·运维·开发语言·php
从此不归路1 小时前
Qt5 进阶【13】桌面 Qt 项目架构设计:从 MVC/MVVM 到模块划分
开发语言·c++·qt·架构·mvc
zhangx1234_1 小时前
C语言 数据在内存中的存储
c语言·开发语言