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

相关推荐
一个闪现必杀技3 分钟前
Python入门--函数
开发语言·python·青少年编程·pycharm
Fan_web6 分钟前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
龙图:会赢的10 分钟前
[C语言]--编译和链接
c语言·开发语言
XKSYA(小巢校长)2 小时前
NatGo我的世界联机篇
开发语言·php
Cons.W2 小时前
Codeforces Round 975 (Div. 1) C. Tree Pruning
c语言·开发语言·剪枝
憧憬成为原神糕手2 小时前
c++_ 多态
开发语言·c++
VBA63372 小时前
VBA信息获取与处理第三个专题第三节:工作薄在空闲后自动关闭
开发语言
立秋67892 小时前
Python的defaultdict详解
服务器·windows·python
wjs20243 小时前
XSLT 实例:掌握 XML 转换的艺术
开发语言
萧鼎3 小时前
Python第三方库选择与使用陷阱避免
开发语言·python