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

相关推荐
东鹏特饮1 小时前
系统运维(传统/通用运维)面试题
开发语言·php
今天要早睡_2 小时前
C++01_入门基础复习
开发语言·c++
黑马程序员毕设3 小时前
基于 Java 的餐饮点餐系统设计与应用报告
java·开发语言
1-1=04 小时前
C# 委托与事件
开发语言·c#
Fuyo_11194 小时前
C++ 运行时多态与虚函数机制全面剖析【面试重点】
开发语言·c++·面试
w_zero_one5 小时前
递归算法(一)
java·开发语言·算法
Julien20046 小时前
管理机密(一)
运维·服务器·开发语言·学习方法
Chen_harmony6 小时前
七、STL与string类
开发语言·c++
沐晓时光6 小时前
C语言入门,字符串和字符串函数知识讲解
c语言·开发语言
xxxiugou1237 小时前
C++命名空间与引用全解析
开发语言·c++