Using C# and P/Invoke to control/automate applications (Think "FindWindow... PostMessage and all that example and class")
Win32 API offers a lot of functionality for Windows platform, which the .NET Framework doesn’t have for good reason – One of them being ‘managed’. However, that doesn’t stop us from doing some unsafe things! We can always build a wrapper for Win32 API and then call those functions directly from .NET.
Let us evaluate one of such area which requires calling Win32 API functions from .NET. That area is ‘Simulating UI Automation’. Of course, the subject is too vast to fit in a single blog post, however, we can start with some basic things at least!
Our objective for this exercise is : “Launch an instance of Notepad and write ‘hello’ in it”; (Sorry for the semicolon, it has become a habit )
So let us start with creating a C# Console application. Next step is to create a new class called Win32 (you can name it whatever you like) and declare a couple of ‘static extern’ methods whose signature should match that of the unmanaged native Win32 API methods. There are a couple of DLLs for core Win32 APIs. You can categorize them into 8 areas. For more info, please visit http://en.wikipedia.org/wiki/Windows_API. We will be focusing on User32.dll for today’s topic as it deals with the ‘User Interface’.
While I've started moving from FindWindow/SendMessage/PostMessage automation to the newer Accessibility API approach, I still thought this class and example good and something I might still need in the future...