C# ManagedWinApi tutorial

31Jan

The C# interop/PInvoke is a good tool: it allows you to call C API directly, and do something which might be hard to get using managed API. I have done quite a few coding using this, and it worked, but the pitfall is that you have to dive deep into the low level APIs, which may distract you from the current focus.

ManagedWinApi is such a kind of tool to make life easier. There are however few article or tutorials, and this post presents my first trial in using this.

I am trying to programmatically input some command to Matlab Command Window, which consists of such window hierarchies (using spy++), as shown below:

The Matlab Command Window is actually an Edit control, and given the Matlab process windows handle (00010C4E), we can enumerate all its child windows, and which in this case only one child (00010C50), and then repeatedly get the leaf window (00010C54), which is the edit control, we can then use SendMessage or PostMessage windows API to send commands to this window, and then programmatically press enter with code!

The Code snippet is as follows:

Here the SystemWindow is a class from ManagedWinApi package, and we can then easily access the child windows with a single line code! I might use tons of code to implemented this myself using PInvoke (e.g. using EnumWindow, GetWindowText, and also write a few callbacks!).

There are many other useful classes in this package, and chm help file is available here. Finally note that you can use Nuget to install this into your existing project: