Ses
Ses

Reputation: 51

How do you focus on a specific window using winapi?

My goal is to make a function similar to this but using an HWND window object as the parameter.

My goal explained:

Say we have 2 (two) app windows. Chrome and Spotify (just an example).
Currently, I have the Chrome window selected.

I want to focus on the Spotify window with a function that uses the Windows API to focus/select the Spotify Window.

The function has 1 parameter that accepts an HWND window object. Then, the function focuses on the window.

It would also be nice to keep the initial size of the window being focused.

What I don't know is the Windows API calls for focusing on certain windows.

Things I've tried:

ShowWindow(hwnd, SW_RESTORE);
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
SetActiveWindow(hwnd);
SetForegroundWindow(hwnd)
SetFocus(hwnd);
SendMessage(hwnd, WM_SETFOCUS, 0, 0);
PostMessage(hwnd, WM_SETFOCUS, 0, 0);

Upvotes: 1

Views: 3388

Answers (1)

xCENTx
xCENTx

Reputation: 101

Probably a little advanced but ... Basically to test out your problem I injected a created a DLL (for simplicity) and injected it into notepad.

First you want to create a console window. This is so that we have a 2nd window to target and we also create a window handle in this process so that we can use it later when we are trying to set window focus.

Next obtain your process id along with the process handle. From there you can loop through all active windows on your pc and compare the WindowID with the Process ID you obtained. We then compare the windows that match the process ID with the input title parameter, when we find a match we can return the window handle.

From here we just create a loop and listen for keypresses to target a window. You first want to set the target window in foreground and then you want to activate it. You CANNOT activate a window unless it is in the foreground.

This is a complete example with the tools required to do it on your own in ANY possible project you might be working on

#include <Windows.h>
#include <iostream>

DWORD dwProcessID;
HANDLE dwHandle;
HWND dwHWND;
HANDLE g_Handle;
HWND g_hWnd;
DWORD exitCode = NULL;

void InitConsole()
{
    AllocConsole();
    freopen_s((FILE**)stdout, "CONOUT$", "w", stdout);
    g_Handle = GetStdHandle(STD_OUTPUT_HANDLE);
    g_hWnd = GetConsoleWindow();
    SetConsoleTitleA(("DEBUG CONSOLE"));
    ShowWindow(GetConsoleWindow(), SW_SHOW);
    printf("Console::Initialized\n");
}

HWND GetWindowHandleByName(const char* Title, DWORD ProcID)
{
    HWND tempHWND = NULL;
    do
    {
        tempHWND = FindWindowEx(NULL, tempHWND, NULL, NULL);
        DWORD tempPID = 0;
        GetWindowThreadProcessId(tempHWND, &tempPID);
        if (tempPID == dwProcessID)
        {
            // Retrieve Window Information
            RECT tempRECT;
            LPSTR tempSTRING[MAX_PATH];
            std::string string;
            GetWindowRect(tempHWND, &tempRECT);
            GetWindowTextA(tempHWND, (LPSTR)tempSTRING, MAX_PATH);
            printf("WindowHandle: %p\nWindowName: %s\n\n", tempHWND, tempSTRING);
            string = reinterpret_cast<const char*>(tempSTRING);
            if (string == Title)
                return tempHWND;
        }
    } while (tempHWND != NULL);
    
    return NULL;    // FAILED
}

void SetWindowFocus(HWND WindowHandle)
{
    SetForegroundWindow(WindowHandle);
    HWND prevWindow = SetActiveWindow(WindowHandle);
    printf("currWindowHandle: %p\nprevWindowHandle: %p\n\n", dwHWND, prevWindow);
}

bool CleanExit(bool State)
{
    fclose(stdout);
    DestroyWindow(g_hWnd);
    FreeConsole();
    ExitThread(State);
}

int SetWindowFocus_Initialize()
{
    InitConsole();
    dwProcessID = GetCurrentProcessId();
    dwHandle = OpenProcess(PROCESS_ALL_ACCESS, NULL, dwProcessID);
    dwHWND = GetWindowHandleByName("Untitled - Notepad", dwProcessID);
    if (!dwHWND)
        return CleanExit(EXIT_FAILURE);
    exitCode = NULL;
    while (GetExitCodeProcess(dwHandle, &exitCode) && exitCode == STILL_ACTIVE) {
        if (GetAsyncKeyState(VK_END)) break;

        if (GetAsyncKeyState(VK_NUMPAD1))
            SetWindowFocus(g_hWnd);

        if (GetAsyncKeyState(VK_NUMPAD2))
            SetWindowFocus(dwHWND);
    }
    return CleanExit(EXIT_SUCCESS);
}

BOOL APIENTRY DllMain( HMODULE hModule, DWORD  dwReason, LPVOID lpReserved )
{
    UNREFERENCED_PARAMETER(hModule);
    UNREFERENCED_PARAMETER(lpReserved);
    if (dwReason == DLL_PROCESS_ATTACH)
        CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)SetWindowFocus_Initialize, NULL, NULL, NULL);
    return TRUE;
}

Upvotes: 4

Related Questions