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. If you are not using any graphics library then you will not have control over the console window easily. Using window.h library function is the only option. Also, I will also like to inform you that we are using windows function so it will not work on Unix/Linux machine.
The sample problem is written in C language and compile in the GCC compiler.

#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);
}

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