1

I am finishing a python program which I will distribute as exe. I use Python 3.7 on Windows 10 64b.

The user will double click on exe to run my program. Then a windows console open and display logs in this console.

My program doesn’t need any gui but I would like to give to the users the possibility to hide the console with the logs and to show it back whenever he/she wants from an icon in the systray.

I found various answers here but none was responding to my needs.

I think I am not the one who would like to have this option on our python script. It could be very useful.

I found a tutorial for building a systray icon in python:

https://youtu.be/WM27fMo5Gg8

But it is about opening windows program, not about showing/hiding its own console.

Gauthier Buttez
  • 1,005
  • 1
  • 16
  • 40

1 Answers1

1

After further investigation, I found the solution. It works when I run my script in the terminal. I still didn't test with the exe of my program. I may come back here to edit my answer if some extra information is necessary for .exe files.

  1. I found this famous script SystrayIcon.py for python 2 which help me to create my icon with a menu very quickly.
  2. I found the Python 3 version of this script here.
  3. Then I use GetConsoleWindow from types and ShowWindow from win32gui to hide and show the console.

    def show(sysTrayIcon):

    the_program_to_hide = ctypes.windll.kernel32.GetConsoleWindow()
    
    win32gui.ShowWindow(the_program_to_hide, win32con.SW_SHOW)
    

    def hide(sysTrayIcon):

    the_program_to_hide = ctypes.windll.kernel32.GetConsoleWindow()
    
    win32gui.ShowWindow(the_program_to_hide, win32con.SW_HIDE)
    

These 2 functions are connected to the menu of my systray icon.

I hope it will help someone one day.

PS: The StackOverflow editor bug and I couldn't manage to show the code of the 2 functions properly.

Gauthier Buttez
  • 1,005
  • 1
  • 16
  • 40
  • This only works with the system console window that's implemented by conhost.exe. It won't work if your program is run from another terminal such as the new Windows Terminal app. But then, it really shouldn't hide an interactive terminal. You should check that the result from `GetConsoleWindow()` isn't `NULL` (0) before attempting to hide the window via `ShowWindow`. It may be 0 in two cases: if executed without a console via the `DETACHED_PROCESS` creation flag or without a window via the `CREATE_NO_WINDOW` creation flag. – Eryk Sun May 08 '20 at 08:48
  • FYI, you can use ctypes to call [`ShowWindow`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow) as well: `user32 = ctypes.WinDLL('user32', use_last_error=True);` `SW_HIDE = 0;` `SW_SHOW = 5`. Then hide via `was_visible = user32.ShowWindow(hwnd, SW_HIDE)`. – Eryk Sun May 08 '20 at 08:50