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

相关推荐
开源技术10 分钟前
如何将本地LLM模型与Ollama和Python集成
开发语言·python
Hello World . .15 分钟前
数据结构:队列
c语言·开发语言·数据结构·vim
clever10127 分钟前
在QtCreator 4.10.2中调试qt程序qDebug()输出中文为乱码问题的解决
开发语言·qt
测试开发Kevin1 小时前
小tip:换行符CRLF 和 LF 的区别以及二者在实际项目中的影响
java·开发语言·python
松☆1 小时前
Dart 核心语法精讲:从空安全到流程控制(3)
android·java·开发语言
编码者卢布2 小时前
【App Service】Java应用上传文件功能部署在App Service Windows上报错 413 Payload Too Large
java·开发语言·windows
kaikaile19952 小时前
结构风荷载理论与Matlab计算
开发语言·matlab
学海无涯书山有路2 小时前
async-await异步编程
c#
切糕师学AI2 小时前
ARM 汇编器中的伪指令(Assembler Directives)
开发语言·arm开发·c#
吕司2 小时前
Qt的信号与槽
开发语言·qt