Search code examples
c#sdl-2avaloniauiavalonia

NativeControlHost with SDL2 not capturing keys


I have application that is written with use of Avalonia and I want to embed into it an SLD2 application (the SDL2 application is written in C# with use of the SDL2-CS wrapper). I used NativeControlHost to get the handle as below:

    public class NativeEmbeddingControl : NativeControlHost
    {
        public IntPtr Handle { get; private set; }

        protected override IPlatformHandle CreateNativeControlCore(IPlatformHandle parent)
        {
            var handle = base.CreateNativeControlCore(parent);
            Handle = handle.Handle;
            return handle;
        }
    }

Then I use this handle when creating an SDL2 window like this:

IntPtr windowPtr = SDL.SDL_CreateWindowFrom(windowHandle);

This works ok for displaying content rendered from the SDL2 application. But it is not getting SDL_KEYDOWN and SDL_KEYUP events when I call SDL_PollEvent.

If I run the SDL2 application as "standalone" (without any embedding) then everything works fine.

Do I need to do anything else to pass key up/down events to the embedded SDL2 app ?


Solution

  • What I ended up doing is to override OnKeyDown and OnKeyUp methods on the main windows of the Avalonia app, and then I am mapping Avalonia.Input.Key enum to SDL.SDL_Keycode enum. After that I am creating a new SDL2 event with a given key down/up like so:

            public void OnKeyUp(SDL.SDL_Keycode key)
            {
                SDL.SDL_Event _event = new SDL.SDL_Event();
                _event.key.keysym.sym = key;
                _event.type = SDL.SDL_EventType.SDL_KEYUP;
                SDL.SDL_PushEvent(ref _event);
            }
    
            public void OnKeyDown(SDL.SDL_Keycode key)
            {
                SDL.SDL_Event _event = new SDL.SDL_Event();
                _event.type = SDL.SDL_EventType.SDL_KEYDOWN;
                _event.key.keysym.sym = key;
                SDL.SDL_PushEvent(ref _event);
            }
    

    Thanks to that I am able to get all key up/down events from the Avalonia into the SDL2 app.