Win32 API không cung cấp bất kỳ phương thức nào để có thể lấy trực tiếp Handle(HWND) của Console Window.
Rất nhiều cửa sổ console có cùng title, vì thế việc lấy handle của Console Window cần tiến hành theo các bước như sau:

1. Lấy title của cửa sổ Console hiện tại bằng GetConsoleTitle
2. Thay đổi title cửa sổ Console bằng SetConsoleTitle để có được một title không trùng
3. Sleep(40) để chắc chắn title được cập nhật
4. Dùng FindWindow với title thu được ở bước 2
5. Thay đổi lại title cho đúng với ban đầu

Sau đây là source code:


Mã:
   HWND GetConsoleHwnd(void)   {       #define MY_BUFSIZE 1024                 // Buffer size for console window titles.       HWND hwndFound;                         // This is what is returned to the caller.       char pszNewWindowTitle[MY_BUFSIZE];    // Contains fabricated WindowTitle.       char pszOldWindowTitle[MY_BUFSIZE];     // Contains original WindowTitle.        // Fetch current window title.       GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);        // Format a "unique" NewWindowTitle.       sprintf(pszNewWindowTitle, "%d/%d", GetTickCount(), GetCurrentProcessId());        // Change current window title.       SetConsoleTitle(pszNewWindowTitle);        // Ensure window title has been updated.       Sleep(40);        // Look for NewWindowTitle.       hwndFound=FindWindow(NULL, pszNewWindowTitle);        // Restore original window title.       SetConsoleTitle(pszOldWindowTitle);        return(hwndFound);   }
Bài viết dịch lược từ MSDN chia sẻ cho thành viên cộng đồng C Việt!