LoginSignup
0
0

More than 1 year has passed since last update.

日記 Visual Studio 2019 C++でフォアグラウンドのexeのフルパスとウインドウタイトルの取得

Last updated at Posted at 2021-08-01

日記

前回の日記「日記 Visual Studio 2019 C++でタスクトレイに常駐するアプリケーションを作成」
次の日記「日記 Visual Studio 2019 C++でSetTimerで定期実行する処理の書き方」

プログラム

やれやれだぜ

GetModuleFileNameExを使用するためのinclude追加

Sample.cpp
// GetModuleFileNameExを使用するため
#include <Psapi.h>

フォアグラウンドのexeのフルパスとウインドウタイトルの取得

Sample.cpp
// フォアグラウンドのウインドウのハンドルを取得
HWND hActWin = GetForegroundWindow();
if (hActWin)
{
    // ウインドウのハンドルからプロセスID取得
    DWORD dwPID;
    GetWindowThreadProcessId(hActWin, &dwPID);

    // プロセスのハンドルを取得
    HANDLE hProcess = OpenProcess(
        PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
        FALSE,
        dwPID
    );

    if (hProcess)
    {
        //// .exe名 非推奨
        //// 32bit64bitが一致していないと取得できない
        //TCHAR exeName[MAX_PATH];
        //if (GetModuleBaseName(hProcess, 0, exeName, MAX_PATH))
        //{
        //}

        // .exeのフルパス
        TCHAR exePath[MAX_PATH];
        if (GetModuleFileNameEx(hProcess, 0, exePath, MAX_PATH))
        {
            TextOut(hdc, 10, 30, exePath, lstrlen(exePath));
        }
        else
        {
            DebugLastError(__FILE__, __LINE__);
        }

        CloseHandle(hProcess);
    }

    // ウインドウテキスト
    int iActWinTextLength = GetWindowTextLength(hActWin);
    if (iActWinTextLength)
    {
        LPTSTR lActWinText = new TCHAR[iActWinTextLength + 1];
        GetWindowText(hActWin, lActWinText, iActWinTextLength + 1);
        TextOut(hdc, 10, 70, lActWinText, lstrlen(lActWinText));
    }
}

WindowsAPIエラー出力

Sample.cpp
// WindowsAPIエラー出力
VOID DebugLastError(const char *file, int line)
{
    DWORD errorCode = GetLastError();
    LPVOID lpMsgBuf;
    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER   // テキストのメモリ割り当てを要求する
        | FORMAT_MESSAGE_FROM_SYSTEM     // エラーメッセージはWindowsが用意しているものを使用
        | FORMAT_MESSAGE_IGNORE_INSERTS, // 次の引数を無視してエラーコードに対するエラーメッセージを作成する
        NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),// 言語を指定
        (LPTSTR)&lpMsgBuf,               // メッセージテキストが保存されるバッファへのポインタ
        0,
        NULL
    );

    char cbuffer[300];
    sprintf_s(cbuffer, sizeof(cbuffer), "%s:(%d)", file, line);
    OutputDebugStringA(cbuffer);
    OutputDebugStringA("\n");

    wchar_t wbuffer[300];
    wchar_t* plpMsgBuf = (wchar_t*)lpMsgBuf;
    wsprintf(wbuffer, L"%ld: %ls", errorCode, plpMsgBuf);
    OutputDebugString((LPCWSTR)wbuffer);

    LocalFree(lpMsgBuf);
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0