我正在努力使我的 wpf 应用程序触摸启用。我已连接到触摸屏辅助显示器。
我面临一个问题。所有触摸事件都被解释为鼠标(单击)事件。使用下面的代码(通过 GPT-4)我尝试获取所有输入设备。
现在奇怪的是,当我逐行调试下面的代码时,触摸事件按预期工作,但是当我正常运行此代码(即没有断点和调试)时,触摸事件不起作用。
可能是什么原因?
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern uint GetRawInputDeviceList(IntPtr pRawInputDeviceList, ref uint puiNumDevices, uint cbSize);
uint deviceCount = 0;
uint size = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(RAWINPUTDEVICELIST));
if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, size) == 0)
{
// Allocate the array for the devices
IntPtr pRawInputDeviceList = System.Runtime.InteropServices.Marshal.AllocHGlobal((int)(size * deviceCount));
// Get the list
GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, size);
// Iterate through the list, processing or displaying device info as needed
for (int i = 0; i < deviceCount; i++)
{
// Marshal the list of RAWINPUTDEVICELIST structs
RAWINPUTDEVICELIST rid = Marshal.PtrToStructure<RAWINPUTDEVICELIST>(
new IntPtr((long)pRawInputDeviceList + (size * i)));
// Process the rid as needed
Debug.WriteLine($"Device Handle: {rid.hDevice}, Type: {rid.dwType}");
}
// Marshal.FreeHGlobal(pRawInputDeviceList);
}
P/Invoke 可以简单得多。
using System.Diagnostics;
using System.Runtime.InteropServices;
internal static class DeviceHelper
{
[DllImport("User32", SetLastError = true)]
private static extern uint GetRawInputDeviceList(
[Out] RAWINPUTDEVICELIST[] pRawInputDeviceList,
ref uint puiNumDevices,
uint cbSize);
[StructLayout(LayoutKind.Sequential)]
private struct RAWINPUTDEVICELIST
{
public IntPtr hDevice;
public uint dwType;
}
public static void FindInputDevices()
{
uint deviceListCount = 0;
uint rawInputDeviceListSize = (uint)Marshal.SizeOf<RAWINPUTDEVICELIST>();
if (GetRawInputDeviceList(
null,
ref deviceListCount,
rawInputDeviceListSize) == 0)
{
var devices = new RAWINPUTDEVICELIST[deviceListCount];
if (GetRawInputDeviceList(
devices,
ref deviceListCount,
rawInputDeviceListSize) == deviceListCount)
{
foreach (var device in devices)
{
Trace.WriteLine($"Handle: {device.hDevice} Type: {device.dwType}");
}
}
}
}
}