Using the Windows API

Leave a comment

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:

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();
        }
    }
}

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:

 

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

See more articles on: C#

Leave a Reply

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