6

Is it possible to change the position of the Windows console through python? If not, is there any workaround?

I don't know if you would need any specific information, but just in case: I'm using Windows 8.1 (64x), Python 3.5.0, the console is being spawned through Popen and the main objective is to move it to the top right corner.

If any info is needed, please let me know.

Eryk Sun
  • 33,190
  • 5
  • 92
  • 111
ArsonFG
  • 315
  • 8
  • 22
  • Step 1, get the window handle to the console. Step 2, move the window. Is the program that is moving the window the one that used `Popen` or the one that is in the console? – Mark Ransom Aug 22 '17 at 22:31
  • Preferably the one that used `Popen` (But if you think it would be easier to do it from "inside", it's not a problem) – ArsonFG Aug 22 '17 at 22:38
  • 1
    Attach to the child's console temporarily via `AttachConsole`. Call `GetConsoleWindow` to get the console window handle. Then detach via `FreeConsole`. Then call `MoveWindow` or `SetWindowPos` to move and resize the console window. – Eryk Sun Aug 24 '17 at 18:10
  • Could you please put it on an answer with an example? Tried, but I think this is a bit too much for me to understand without an example... (Sorry, still learning the basics of python) – ArsonFG Aug 24 '17 at 20:51

1 Answers1

4

I adapted this from an answer by NYMK

This will move and resize a single command prompt window (opened by CMD). It is simple and does not handle errors, multiple command prompt windows or command line.

import win32gui

appname = 'Command Prompt'
xpos = 50
ypos = 100
width = 800
length = 600

def enumHandler(hwnd, lParam):
    if win32gui.IsWindowVisible(hwnd):
        if appname in win32gui.GetWindowText(hwnd):
            win32gui.MoveWindow(hwnd, xpos, ypos, width, length, True)


win32gui.EnumWindows(enumHandler, None)

for a full commandline ready - try:

import win32gui
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("app_name", type=str, default='Command Prompt', help="The window name")
parser.add_argument("xpos", type=int,  default=0, help="x position: 0 or greater")
parser.add_argument("ypos", type=int,  default=0, help="y position: 0 or greater")
parser.add_argument("width", type=int, default=100, help="window width: 10 or greater")
parser.add_argument("length", type=int, default=100, help="window length: 10 or greater")

args = parser.parse_args()

appname = args.app_name
xpos = args.xpos
ypos = args.ypos
width = args.width
length = args.length


def enumHandler(hwnd, lParam):
    if win32gui.IsWindowVisible(hwnd):
        if appname in win32gui.GetWindowText(hwnd):
            win32gui.MoveWindow(hwnd, xpos, ypos, width, length, True)


win32gui.EnumWindows(enumHandler, None)
DarkLight
  • 79
  • 3
  • 16