Saturday, March 19, 2011

Resize and Move Console Window in C/C++ using windows function

This is another article related to the window.h library function. Here I will take you through resizing the console window and moving it on the screen at the desire position. Using window.h library function is the only option to control console windows if you are not using third-party graphics library. Resizing and moving console window function is useful if your application needs to create multiple windows and position it as per requirement. 
Note: Below sample C code works only in the windows environment.

#include <windows.h>
#include <stdio.h>

HWND WINAPI GetConsoleWindowNT(void)
{
    //declare function pointer type
    typedef HWND WINAPI(*GetConsoleWindowT)(void);
    //declare one such function pointer
    GetConsoleWindowT GetConsoleWindow;
    //get a handle on kernel32.dll
    HMODULE hk32Lib = GetModuleHandle(TEXT("KERNEL32.DLL"));
    //assign procedure address to function pointer
    GetConsoleWindow = (GetConsoleWindowT)GetProcAddress(hk32Lib
    ,TEXT("GetConsoleWindow"));
    //check if the function pointer is valid
    //since the function is undocumented
    if(GetConsoleWindow == NULL){
        return NULL;
    }
    //call the undocumented function
    return GetConsoleWindow();
}
int main()
{
    HWND hWnd=GetConsoleWindowNT();
    MoveWindow(hWnd,1230,600,300,200,TRUE);
}
I suggest you to test the parameters values of the function MoveWindow because the maximum value depends upon the size of the laptop or monitor screen.

3 comments:

  1. THANK YOU - I was wondering if I had to call some windows to get this working -- apparently yes.

    ReplyDelete
  2. THANK YOU so much bro! You saved my day! Keep up the good work.

    ReplyDelete
  3. Thank you for the useful script. But I`m often faced with such mistake as Cannot find kernel32.dll. know that this file http://fix4dll.com/kernel32_dll bug fixes if unzip it into the installation folder. Good luck!

    ReplyDelete