Home › C# › Using the Windows API
C# · Nov 18, 2016 · 1 MIN READ

Using the Windows API

In this post, we will look at how to use the Windows API to get and set windows in the Windows operating system.

First, create a new console app:

We will firstly add the Interop Services, which allows us to enable interop with DLLs:

using System.Runtime.InteropServices;

In our case, we will be using the user32.dll.

Next, we will use DllImport, which is part of the namespace we added, to reference the dll:

[DllImport("user32.dll")]

Finally, we can call a window function. In our case, we will call GetForegroundWindow. and print it to the console app:

[sourcecode language=”csharp”] using System;
using System.Text;
using System.Runtime.InteropServices;

namespace Carl.WindowsAPITest
{
class Program
{
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();

static void Main(string[] args)
{
IntPtr handle = GetForegroundWindow();
Console.ReadLine();
}
}
}
[/sourcecode]

Running this, we can see the what the handle returns:

We can also open Spy++ to see the handle value. To do this, in Visual Studio select Spy++:

This will open:

Select the Window Finder and drag the icon into the console app to see the same window handle:

 

 

Carl de Souza
Keep learning. Keep building.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.

Subscribe on YouTube →
Carl de Souza Enterprise Architect at Microsoft · AI Technology Expert

Leave a Reply

Your email address will not be published. Required fields are marked *

Carl de Souza
KEEP LEARNING. KEEP BUILDING.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.