IntergatedCircuits / HidSharp

HIDSharp is a multiplatform C# library for USB HID devices by James F. Bellinger
https://www.zer7.com/software/hidsharp
Other
117 stars 33 forks source link

Freezing host application (unity freezing) #33

Open devingDev opened 1 month ago

devingDev commented 1 month ago

I'm on windows using Unity 2022.3.28f1 and the current latest commit on this repo. I tried the nuget package and also this, but neither works perfectly inside Unity.

The second time I press play it freezes up and I have to force stop it in task manager.

Found this but i don't know how to fix it right now: https://forum.zer7.com/topic/10126/

devingDev commented 1 month ago

Fixed it this way if anyone cares: In WinHidManager.cs

  1. Change this part in the Run method:
NativeMethods.MSG msg;
while (true)
{
    int result = NativeMethods.GetMessage(out msg, hwnd, 0, 0);
    if (result == 0 || result == -1) { break; }

    NativeMethods.TranslateMessage(ref msg);
    NativeMethods.DispatchMessage(ref msg);
}

to:

NativeMethods.MSG msg;
_hwnd = hwnd;
while (true)
{
    int result = NativeMethods.GetMessage(out msg, hwnd, 0, 0);
    if (result == 0 || result == -1) { break; }

    NativeMethods.TranslateMessage(ref msg);
    NativeMethods.DispatchMessage(ref msg);
}
  1. After or before the Run method add this:
        static IntPtr _hwnd;
        public static void QuitThisBs()
        {
            uint WM_QUIT = 0x0012;
            if (_hwnd != IntPtr.Zero)
            { 
                PostMessage(_hwnd, WM_QUIT, IntPtr.Zero, IntPtr.Zero);
            }
        }

        [DllImport("user32.dll")]
        static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
  1. In your code where you exit or want to stop it call WinHidManager.QuitThisBs(); (For me I did it in the OnDestroy method Unity provides, but you can call it anywhere even prematurely while game is still running)

  2. Done!

benedekkupper commented 1 month ago

Thanks for your report and investigation on the fix! Care to open a PR with these changes?