How to use Interop Services in C# (Focus on external window)
Hello everyone, in this article we are going to talk about interoperability through interop services and how to use unmanaged code in C#. We are going to reach the code that does not CLR in C# and visual Studio.Let's begin.
We can use the libraries and the developed API's which developed with unmanaged code. So we can gain some time for our projects and we can take the advantages of the existing APIs. For example windows has own APIs. But most of them are not managed code or we can use another api with C or C++ programming languages or some ActiveX and COM components. In these cases we are going to need the Interop services to use them in our C# CLR programs.
In our example we are going to reach the some windows APIs to get the some values easly. We may write so many codes to do same things in our C# program.
We are going to find a window with its specified Title and focus it. After it we are going to send some keys and pressings in it.
using System.Runtime.InteropServices;
And the we are define the prototype methods of the C language API that we are going to use. We are importing the library with DllImport method and the we defined function prototype from the imported API like below.
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
public static void StartAndWrite()
{
IntPtr windowPointer = IntPtr.Zero;
int processCount = 100;
for (int i = 0; (i < processCount) && (windowPointer == IntPtr.Zero); i++)
{
windowPointer = FindWindow(null, "exampleNotepad.txt - Not Defteri");
}
if (windowPointer != IntPtr.Zero)
{
SetForegroundWindow(windowPointer);
Thread.Sleep(500);
SendKeys.SendWait("BurakHamdiTUFAN");
SendKeys.SendWait(Environment.NewLine);
SendKeys.SendWait("Thecodeprogram");
SendKeys.SendWait("{ENTER}");
SendKeys.Flush();
}
}
Just make sure the application with specified title has been started. Because this method is looking for the running processes to be focused.
You can rach the example application on Github : https://github.com/thecodeprogram/InteropServices_Example
That is all in this article.
Have a good Interop Servicing.
Burak Hamdi TUFAN
Comments