Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting HWND off of CoreWindow object in UWP

Tags:

c#

uwp

hwnd

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, please.

https://msdn.microsoft.com/en-us/library/dn302119(v=vs.85).aspx

like image 685
gt6707a Avatar asked Jan 21 '16 21:01

gt6707a


1 Answers

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;
like image 89
Hans Passant Avatar answered Nov 08 '22 21:11

Hans Passant