Sheldon
Sheldon

Reputation: 116

How to print the title of the active window in C - WinAPI

Well i have only one semester of C so i am little confused with HWND and how to use it. I just want to print active window. I found - GetActiveWindow, GetForegroundWindow.

But i just dont understand how to use this function to print that active window.

I was trying to do something like.

HWND GetActiveWindow();
printf("%s", GetActiveWindow);

But that is probably bad use and not working.
If someone can gave me a working example i will be very thankfull.

Upvotes: 2

Views: 794

Answers (2)

Govind Parmar
Govind Parmar

Reputation: 21572

An HWND is a handle. It has an integral value, not a string value. If your intent is to print out the title of the window, you can first use the GetWindowTextLengthW to get the character length of the window title, allocate memory for it, then use the GetWindowText function to obtain a title from an HWND:

#include <Windows.h>
#include <sal.h>

BOOL PrintWindowTitle(_In_ HWND hWnd)
{
    INT nLen = GetWindowTextLengthW(hWnd);
    WCHAR *wszTitle = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (nLen + 1) * sizeof(WCHAR));

    if(NULL == wszTitle)
    {
        SetLastError(ERROR_OUTOFMEMORY);
        return FALSE;
    }

    GetWindowTextW(hWnd, wszTitle, nLen);
    wprintf(L"%s\n", wszTitle);

    HeapFree(GetProcessHeap(), 0, wszTitle);
    wszTitle = NULL;

    SetLastError(ERROR_SUCCESS);
    return TRUE;
}

Upvotes: 3

i486
i486

Reputation: 6570

TCHAR buf[256], out[280];

GetWindowText( GetActiveWindow(), buf, sizeof buf / sizeof *buf );
wsprintf( out, TEXT( "Window text: %s\n" ), buf );

Upvotes: 2

Related Questions