How to script clicking on "X" to close window

rated by 0 users
Not Answered This post has 0 verified answers | 2 Replies | 2 Followers

Not Ranked
3 Posts
shahab posted on 11-11-2012 4:10 PM


I'm a newbie to Powershell.   I'm trying to write a script that will close some applications running on a server gracefully.    The apps are running in CMD windows and the correct procedure to close them is to just click on the "X" in the upper right hand corner.   I assumed that the Alt+F4 keystroke combination would approximate that, but that doesn't work.   Any suggestions would be much appreciated.   My code is:

#Stop running processes on a Test server
add-type -AssemblyName microsoft.VisualBasic
add-type -AssemblyName System.Windows.Forms

I have also tried without any success:

add-type -AssemblyName microsoft.VisualBasic
add-type -AssemblyName System.Windows.Forms


All Replies

Top 10 Contributor
2,170 Posts
Microsoft MVP
Top Contributor

I don't think this is the most robust approach. the alt+f4 won't work for cmdline window and sending alt+space c is dependent on system localization. Or maybe not even possible using sendwait.

you can use windows API for this purpose as shown here:

and here I adapted this call for powershell:


Add-Type -Name ConsoleUtils -Namespace WPIA -MemberDefinition @'
        public static extern int FindWindow(string lpClassName,string lpWindowName);
        public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_CLOSE = 0xF060;

#find console window with tile "test" and close it. 
[int]$handle = [WPIA.ConsoleUtils]::FindWindow('ConsoleWindowClass','test')
if ($handle -gt 0)
    [void][WPIA.ConsoleUtils]::SendMessage($handle, [WPIA.ConsoleUtils]::WM_SYSCOMMAND, [WPIA.ConsoleUtils]::SC_CLOSE, 0)
Not Ranked
3 Posts

Thanks for the suggestion, I will look into it.   Though the code is a bit more complex than what I was looking for.



Page 1 of 1 (3 items) | RSS
Copyright 2012 All rights reserved.