How to use Windows API in Qt (A simple example)

Qt is a cross-platform framework that encapsulates API across many Operating Systems but one always faces situations in which he/she needs to access and use OS specific capabilities. Windows API is a massive collection of interfaces that allow a programmer to use and include Windows features in their programs.  Below is a simple example on how to use Windows API in Qt.

Let’s say we want to use GetSystemTime function in our Qt program. Searching Google for “GetSystemTime API” you’ll get the API Documentation from MSDN website. Parameters and return type values should be obvious:

void WINAPI GetSystemTime(_Out_ LPSYSTEMTIME lpSystemTime);


As seen in the definition, there are not return values and the input parameter is a pointer to SYSTEMTIME structure:

typedef struct _SYSTEMTIME {
	WORD wYear;
	WORD wMonth;
	WORD wDayOfWeek;
	WORD wDay;
	WORD wHour;
	WORD wMinute;
	WORD wSecond;
	WORD wMilliseconds;
} SYSTEMTIME, * PSYSTEMTIME;

Search for the requirements on the page and you’ll see the following:
Requirements:
Minimum supported client: Windows 2000 Professional [desktop apps | Windows Store apps]
Minimum supported server: Windows 2000 Server [desktop apps | Windows Store apps]
Header: Winbase.h (include Windows.h)
Library: Kernel32.lib
DLL: Kernel32.dll

This means you need to include “Windows.h” in your program by adding the following line:

#include "Windows.h"

You also need to add the library reference to your project by adding the following line to your PRO file:

LIBS += -lKernel32


And finally you need to have Kernel32.DLL where your application can access it. You need to either copy it to the folder where your application resides or add it to PATH. (in this case, Kernel32 is in Windows System folder which is already added to path so you can just skip doing this step.)

In fact the same procedure applies to any other framework or API that you want to use in C++. You need to do three simple steps:
1. Add include files to your program’s source
2. Add Library reference to your project
3. Make the DLL files visible to your application’s executable (This step can be omitted if you have access to Static libraries of the framework you are using)



Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.