Open In App

How to Hide the Console Window of a C Program?

Last Updated : 11 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The task is to hide the console window of a C program. The program for the same is given below.

Note: The results of the following program can only be seen when it is executed on a console. 

C




// C program to hide the console window
#include <stdio.h>
#include <windows.h>
 
int main()
{
    HWND myWindow = GetConsoleWindow();
    printf("Hiding the window\n");
    Sleep(3000);
    ShowWindow(myWindow, SW_HIDE);
 
    return 0;
}


Output:

hide the console window

 

Explanation: The execution of the program can be understood by understanding the key functions of the program.

  • #include<windows.h> – The windows.h header in C and C++ programming languages are specifically designed for windows and contain a very large number of windows specific functions.
  • HWND – HWND is used to identify a Windows window. HWND is of data type ‘Handle to a Window’ and it keeps a track of objects that appear on the screen.
  • GetConsoleWindow() – The GetConsoleWindow() is a function that takes no parameters and returns a handle to the window used by the console associated with the calling process or NULL if there is no such associated console.
  • ShowWindow() – The ShowWindow() function controls how a window will be displayed on the device.  SW_HIDE is used to hide the window.
  • Sleep() – It is a function in many programming languages that causes the program to pause execution for a specified amount of time. This is useful for delaying execution or creating time intervals between events.

Since the console window is just hidden, the execution of the program continues in the background of the device. 

Example:

C




// C program to hide the console window
#include <stdio.h>
#include <windows.h>
 
int main()
{
    HWND myWindow = GetConsoleWindow();
    printf("Hiding the window\n");
 
    Sleep(3000);
    ShowWindow(myWindow, SW_HIDE);
 
    Sleep(3000);
    ShowWindow(myWindow, SW_SHOW);
 
    printf("The window is displayed again!");
 
    return 0;
}


Output:

hide the console window

 

Explanation: The above program initially waits for the specified time and hides the console window and then again displays the window after the specified time. SW_SHOW is used to activate the window and display it. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads