简体   繁体   中英

Get receive keyboard an mouse events from SDL2 in WPF application

I'm trying to capture mouse and keyboard events from SDL2 using the SDL2-CS binding library. The events are polled for but these events are never raised.

I think this is because the polling needs to happen on the UI thread. I tried initializing SDL from the UI thread by calling App.Current.Dispatcher.Invoke(Init) but no events are polled.

Basic implementation of my class:

public override void Initialize()
{
    if (hooked)
    {
        return;
    }

    App.Current.Dispatcher.Invoke(Init); //Run on the UI thread        
}

private void Init()
{
    var init = SDL.SDL_Init(SDL.SDL_INIT_VIDEO);
    if (init != 0)
    {
        throw new Exception("Could not initialize SDL");
    }
    hooked = true;
    ListenForEvents();

}

private void ListenForEvents()
{
    SDL.SDL_Event ev;
    while (true)
    {
        if (SDL.SDL_PollEvent(out ev) != 1) //This is continuously trigged
        {
            continue;
        }

        switch (ev.type) //This is never reached
        {
            case SDL.SDL_EventType.SDL_MOUSEMOTION:
                if (MouseMoved != null) { MouseMoved(this, ev.motion); }
                break;

            ...
        }
    }
}

I'm wondring if I'm invoking the Init on the UI thread wrong, or if the SDL initialization is wrong.

PS Hooking with user32.dll is not desired because this code will run on non windows environments as well.

Looking at your code I would say your UI is blocked because ListenForEvents is not running on a different thread and invoking the Init call will run the method - that never returns - on the UI thread.

It might be a good idea to call Init invoked, but then you should start a new thread for polling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM