在.NET Framework 4.7中检测Windows Game Bar激活及输入重定向的问题
在.NET Framework 4.7 WinForms中检测Windows Game Bar状态及输入重定向
无需依赖第三方NuGet包,直接通过P/Invoke调用Windows原生API即可实现需求,以下是C#和VB.Net的实现代码:
C# 实现
检测工具类
using System; using System.Runtime.InteropServices; public static class GameBarDetector { [DllImport("windows.gaming.ui.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] private static extern bool IsGameBarPresent(); [DllImport("windows.gaming.ui.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] private static extern bool IsGameBarRunning(); [DllImport("user32.dll", SetLastError = true)] private static extern bool GetWindowDisplayAffinity(IntPtr hWnd, out uint pdwAffinity); private const uint WDA_MONITOR = 0x00000001; public static bool IsGameBarEnabled() { try { return IsGameBarPresent() && IsGameBarRunning(); } catch (DllNotFoundException) { return false; } } public static bool IsInputRedirected(IntPtr windowHandle) { if (!IsGameBarEnabled()) return false; if (GetWindowDisplayAffinity(windowHandle, out uint affinity)) { return (affinity & WDA_MONITOR) != 0; } return false; } }
WinForms中调用示例
private void CheckGameBarState() { bool isGameBarActive = GameBarDetector.IsGameBarEnabled(); bool isInputRedirected = GameBarDetector.IsInputRedirected(this.Handle); MessageBox.Show($"Game Bar状态:{(isGameBarActive ? "已开启" : "未开启")}\n输入重定向:{(isInputRedirected ? "是" : "否")}"); }
VB.Net 实现
检测工具模块
Imports System Imports System.Runtime.InteropServices Public Module GameBarDetector <DllImport("windows.gaming.ui.dll", CharSet:=CharSet.Unicode, ExactSpelling:=True)> Private Function IsGameBarPresent() As Boolean End Function <DllImport("windows.gaming.ui.dll", CharSet:=CharSet.Unicode, ExactSpelling:=True)> Private Function IsGameBarRunning() As Boolean End Function <DllImport("user32.dll", SetLastError:=True)> Private Function GetWindowDisplayAffinity(hWnd As IntPtr, ByRef pdwAffinity As UInteger) As Boolean End Function Private Const WDA_MONITOR As UInteger = &H1 Public Function IsGameBarEnabled() As Boolean Try Return IsGameBarPresent() AndAlso IsGameBarRunning() Catch ex As DllNotFoundException Return False End Try End Function Public Function IsInputRedirected(windowHandle As IntPtr) As Boolean If Not IsGameBarEnabled() Then Return False End If Dim affinity As UInteger If GetWindowDisplayAffinity(windowHandle, affinity) Then Return (affinity And WDA_MONITOR) <> 0 End If Return False End Function End Module
WinForms中调用示例
Private Sub CheckGameBarState() Dim isGameBarActive As Boolean = GameBarDetector.IsGameBarEnabled() Dim isInputRedirected As Boolean = GameBarDetector.IsInputRedirected(Me.Handle) MessageBox.Show($"Game Bar状态:{If(isGameBarActive, "已开启", "未开启")}{vbCrLf}输入重定向:{If(isInputRedirected, "是", "否")}") End Sub
测试说明
- 检测Game Bar开启状态:按下
Win+G打开Game Bar,调用方法后返回值应为True。 - 检测输入重定向:在Game Bar中启动录制或截屏功能,目标窗口的
IsInputRedirected方法会返回True。 - 兼容性:
windows.gaming.ui.dll仅存在于Windows 10 1607及以上版本,代码已处理DLL未找到的异常,可兼容旧系统。
内容的提问来源于stack exchange,提问作者smoorke
相关产品推荐
相关产品推荐

