此文记录的是检测桌面窗体的小函数。
/***
桌面窗体工具类库
Austin Liu 刘恒辉
Project Manager and Software Designer
E-Mail: lzhdim@163.com
Blog: http://lzhdim.cnblogs.com
Date: 2024-01-15 15:18:00
说明:
用于判断桌面是否有窗体显示,桌面是否被遮挡的判断。
使用方法:
bool _Index = DesktopWindowUtil.IsHaveShowWindow();
bool _Index = DesktopWindowUtil.IsDesktopCovered();
***/
namespace Lzhdim.LPF.Utility
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
/// <summary>
/// 桌面窗体工具类
/// </summary>
public class DesktopWindowUtil
{
#region 判断桌面是否显示了窗体
private const int GWL_STYLE = -16;
private const int WS_VISIBLE = 262144;
/// <summary>
/// 判断桌面是否显示了窗体
/// </summary>
/// <returns>true 桌面有窗体显示;false 桌面没窗体显示;</returns>
public static bool IsHaveShowWindow()
{
IntPtr hWnd = GetForegroundWindow();
bool isVisible = IsWindowVisible(hWnd); // 检查窗体是否可见
int style = GetWindowLong(hWnd, GWL_STYLE); // 获取窗体样式
bool isNotMinimized = (style & WS_VISIBLE) == WS_VISIBLE; // 检查窗体是否最小化
if (isVisible && isNotMinimized)
{
return true;
}
else
{
return false;
}
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWindowVisible(IntPtr hWnd);
#endregion 判断桌面是否显示了窗体
#region 判断桌面是否被遮挡
/// <summary>
/// 判断桌面是否被覆盖
/// </summary>
/// <returns></returns>
public static bool IsDesktopCovered()
{
List<IntPtr> handles = GetAllWindowHandles();
foreach (IntPtr handle in handles)
{
bool isVisible = IsWindowVisible(handle); // 检查窗体是否可见
int style = GetWindowLong(handle, GWL_STYLE); // 获取窗体样式
bool isNotMinimized = (style & WS_VISIBLE) == WS_VISIBLE; // 检查窗体是否最小化
//只要有一个窗体为最大化,而且已经显示并且不是最小化,则认为桌面有窗体被遮挡
if (IsZoomed(handle) && isVisible && isNotMinimized)
{
return true;
}
}
return false;
}
#region 私有方法
private static List<IntPtr> windowHandles = new List<IntPtr>();
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
private static bool EnumTheWindows(IntPtr hWnd, IntPtr lParam)
{
// 将窗口句柄添加到列表中
windowHandles.Add(hWnd);
// 继续枚举其他窗口
return true;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
private static List<IntPtr> GetAllWindowHandles()
{
// 清除之前的句柄列表(如果需要)
windowHandles.Clear();
// 枚举所有顶级窗口
EnumWindows(new EnumWindowsProc(EnumTheWindows), IntPtr.Zero);
// 返回找到的窗口句柄列表
return windowHandles;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsZoomed(IntPtr hWnd);
#endregion 私有方法
#endregion 判断桌面是否被遮挡
}
}