sergtk
sergtk

Reputation: 10974

How to call native code which draw in WPF Image from C# code?

I have a native library (no sources available) wrapped into C# code.

The following C# declaration exists:

[DllImport(DRIVER_DLL_NAME, 
 CallingConvention = CallingConvention.Cdecl, 
 EntryPoint = "RenderBitmap")]
private static extern int RenderBitmap(int hWnd);

I need to call this function from my WPF C# project.

I have a working sample code for Windows forms:

System.Windows.Forms.PictureBox DisplayWindow;
...
RenderBitmap(DisplayWindow.Handle.ToInt32());

And I have not found how to do so with WPF System.Windows.Controls.Image instead of System.Windows.Forms.PictureBox - there is no Handle property or something similar.

Moreover I found in "WPF and Win32 Interoperation" the following statement: "When you create a WPF Window, WPF creates a top-level HWND, and uses an HwndSource to put the Window and its WPF content inside the HWND. The rest of your WPF content in the application shares that singular HWND.". It seems that HWND handle does not exist at all for Image.

How to call native code which draw in WPF Image from C# code?

Upvotes: 2

Views: 1447

Answers (1)

sll
sll

Reputation: 62484

WPF Controls does not have handles like in WinForms. Only main window handle is accessible:

For instance, in main window class (or use Application.Current.MainWindow):

 var handle = (new WindowInteropHelper(this)).Handle;
 var hwnd = HwndSource.FromHwnd(handle);

So looks like you've to consider another approach instead of native calls.

BTW, why you need such a low level drawing functionality? I just can assume that you simply want to reuse already implemented one for WinForms. Perhaps you can achieve the same using built in WPF features.

Upvotes: 3

Related Questions