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

相关推荐
冰冷的希望4 分钟前
【系统】非虚拟机,物理机安装Ubuntu教程,Windows与Linux(Ubuntu)双系统共存!
linux·windows·ubuntu·系统架构·vmware·双系统·pe系统
jwn9998 分钟前
PHP vs C:语言特性与应用场景对比
c语言·开发语言·php
不想看见40412 分钟前
在AI时代下,刷LeetCode题的价值与意义
开发语言·c++·qt
jwn99913 分钟前
PHP与C++:Web脚本与系统编程的终极对决
java·开发语言
hnlgzb15 分钟前
Companion Object - 伴生对象 类比java中的什么?
java·开发语言
T0uken15 分钟前
【Python】uvpacker:跨平台打包 Windows 应用
开发语言·python
我还为发觉19 分钟前
2026 PHP入门到精通全实操(环境部署+框架实战)
开发语言·php
南境十里·墨染春水23 分钟前
C++ 笔记 多重继承 菱形继承(面向对象)
开发语言·c++·笔记
Albert Edison25 分钟前
【ProtoBuf 语法详解】选项 option
开发语言·c++·序列化·反序列化·protobuf
墨雪不会编程27 分钟前
C++容器适配器【困难篇】双向队列详解
开发语言·c++