How to show/hide windows console in systray?

1k Views Asked by At

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.

1

There are 1 best solutions below

2
Gauthier Buttez On

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.