Getting HWND off of CoreWindow object in UWP

后端 未结 3 1933
太阳男子
太阳男子 2020-12-03 09:18

This short MSDN documentation says CoreWindow has ICoreWindowInterop that obtains the handle HWND to the CoreWindow. But I cannot find references on how to get it (C#). Help

相关标签:
3条回答
  • This COM interface is only directly accessible to C++ code. In C# you have to declare it yourself and make it match the interface declaration in C:\Program Files (x86)\Windows Kits\10\Include\10.0.10586.0\winrt\CoreWindow.idl. Like this:

    using System.Runtime.InteropServices;
    ...
        [ComImport, Guid("45D64A29-A63E-4CB6-B498-5781D298CB4F")] 
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        interface ICoreWindowInterop {
            IntPtr WindowHandle { get; }
            bool MessageHandled { set; }
        }
    

    Obtaining the interface reference requires casting, the compiler won't let you cast from the CoreWindow object directly. It is most easily done by letting the DLR get the job done, like this:

        dynamic corewin = Windows.UI.Core.CoreWindow.GetForCurrentThread();
        var interop = (ICoreWindowInterop)corewin;
        var handle = interop.WindowHandle;
    
    0 讨论(0)
  • 2020-12-03 09:28

    Please note there are no supported APIs for UWP that accept an HWND. Any API you call will fail Windows Store certification, and even if you avoid the Windows Store (eg, side-load or go through an Enterprise deployment) there is no guarantee the app will work in the future.

    0 讨论(0)
  • 2020-12-03 09:39

    there are no supported APIs for UWP that accept an HWND

    While generally UWA apps should never reason about HWNDs there are many WinRT APIs that support accepting HWNDs to support use from Win32 Apps. Here is an example and another. C# clients will need to use interop techniques, here is an example of that.

    0 讨论(0)
提交回复
热议问题