How to script clicking on "X" to close window

rated by 0 users
This post has 2 Replies | 2 Followers

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

Hi,

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
[Microsoft.VisualBasic.Interaction]::AppActivate("TestProcessor")
add-type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait("%F4")

I have also tried without any success:

add-type -AssemblyName microsoft.VisualBasic
[Microsoft.VisualBasic.Interaction]::AppActivate("TestProcessor")
add-type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait("Exit")

Shahab

Top 10 Contributor
Posts 1,749
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:

http://www.codeproject.com/Articles/22257/Find-and-Close-the-Window-using-Win-API

and here I adapted this call for powershell:

 

Add-Type -Name ConsoleUtils -Namespace WPIA -MemberDefinition @'
[DllImport("user32.dll")]
        public static extern int FindWindow(string lpClassName,string lpWindowName);
        [DllImport("user32.dll")]
        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
Posts 3

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

 

Shahab

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