- Close programs from the command line (Windows)
- 5 Answers 5
- Update to Updated Question
- How to bind Close command to a button
- 7 Answers 7
- MainWindow.xaml.cs (Or other Code-Behind)
- MainWindow.xaml (Or anything that implements CommandBindings)
- How to prevent auto-closing of console after the execution of batch file
- 17 Answers 17
- WPF MVVM: How to close a window
- 21 Answers 21
Close programs from the command line (Windows)
What is the proper way to close/exit programs from command line, similar to pressing the «X» close button in the corner of the window?
Im trying to close chrome under 3 different versions of windows: win7 ultimate, win7 home, winXP
Under Ultimate and XP: TSKILL chrome
Under Home: TASKKILL /IM chrome.exe
(It closes chrome, no cmd errors,
but chrome error restore when relaunch it)
TASKKILL /IM chrome.exe :
(It closes chrome, no chrome errors when relaunch it,
but errors in cmd: «impossible to terminate child processes(about 4-5), only by force with /F «)
Should I ignore cmd child errors if on relaunch chrome show me no errors?
5 Answers 5
The proper way to close/exit a program ultimately depends upon the software. However, generally the best practice is for Windows programs to close whenever they receive the WM_CLOSE message. Properly releasing memory and closing handles. There are other messages that can signal the close of the application, but it is up to the author of the software how each message is handled.
taskkill sends the WM_CLOSE message and it is then up to the application whether to properly close. You may also want to use the /T option to also signal child processes.
Only use the /F option if you want to force the termination of the process.
Other options would include sending the Alt+F4 keys, using PowerShell, or 3rd party applications.
Update to Updated Question
Ignore, the errors. Chrome generates many processes. The errors are caused when an process does not acknowledge the WM_CLOSE message that TASKKILL sends. Only processes with a message loop will be able to receive the message, therefore, the processes that do not have a message loop will generate that error. Most likely, these processes are the chrome extensions and plugins.
To hide the errors capture the output
Summary: TASKKILL is the proper way via command line to close applications per its WM_CLOSE implementation and the Microsoft KB that I linked.
It has «closeprocess» command which is designed to close processes gracefully. As per its document, it does not terminate apps but sends WM_CLOSE to all top-level windows of the target process.
If this doesn’t work, I bet your application has an unusual cleanup procedure. I would like to see what happens inside so please let me know what your target application is.
The answer to that question can be found here (Microsoft link).
You can send WM_CLOSE messages to any window you wish to close. Many windows handle WM_CLOSE to prompt the user to save documents.
A tool that does this correctly is @Kill . Look also SendMsg.
I do not know how to do this in batch, but you could use the vbscript for this. Simulating the Alt + F4 keys (equates to signal WM_CLOSE ).
Run and look at the behavior of this script below.
Here is the list key names for SendKeys.
When you run the script, the notepad is open, some words are written and then a signal to close the program is delivered, see picture below.
Additional Questions
Can I start a program minimized, or background with vbscript?
Yes. Use the following code:
For more information check the Run Method .
Can chrome go to some url in vbscript?
If chrome is the default, use:
Is there a way to bring focus to specific application (chrome.exe)?
I want to send alt+f4 ONLY to chrome, independently of i’m doing with other windows.
The following code works on Windows 8.
There are some command-line utilities that can send a suitable WM_SYSCOMMAND message (with SC_CLOSE as the command) to a program’s top-level window. I’m sure that at least one will be mentioned shortly. (Then someone will mention AutoIt. Then there’ll be an answer showing how to do it with PowerShell and CloseMainWindow() .)
The command-line utility that comes as a built-in command in JP Software’s TCC, a command interpreter and command script processor for Windows, is called TASKEND .
Alright, Not going to lie. I saw this on stackoverflow and thought it was a challenging question. Soooo I just spent the last 2 hours writing some code. And here it is.
After following the steps below, you can type «TaskClose notepad.exe» after hitting «Start» and it will auto save all undocumented notepad files into desktop. It will auto-close chrome.exe and save the restoration settings.
You can add and remove additional settings for other applications under the if conditions. For instance:
The vbs and batch files performs the following procedures:
- Collects the executable.
- Queries the executable application names off of the tasklist.
- Performs an «Alt+TAB(x)» procedure until it has verified the window is open.
- Then Executes the rolling commands whether it be «Alt+F4» or even in extreme cases
- Alt+F4
- Activate Save
- AutoIncrememnt Filename
- Exit application.
ReturnAppList.bat : install in «C:\windows\system32\»
TaskClose.bat : install in «C:\windows\system32\» AND «C:\Users\YourUserName\»
TaskClose.vbs : install in «C:\windows\system32\»
This was alot of fun to write and I’m more happy about finishing it than actually showing the answer. Have a great week!
How to bind Close command to a button
The easiest way is to implement ButtonClick event handler and invoke Window.Close() method, but how doing this through a Command binding?
7 Answers 7
I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:
All it takes is a bit of XAML.
Actually, it is possible without C# code. The key is to use interactions:
In order for this to work, just set the x:Name of your window to «window», and add these two namespaces:
This requires that you add the Expression Blend SDK DLL to your project, specifically Microsoft.Expression.Interactions .
In case you don’t have Blend, the SDK can be downloaded here.
If the window was shown with Window.ShowDialog() :
The simplest solution that I know of is to set the IsCancel property to true of the close Button :
No bindings needed, WPF will do that for you automatically!
This properties provide an easy way of saying these are the «OK» and «Cancel» buttons on a dialog. It also binds the ESC key to the button.
For .NET 4.5 SystemCommands class will do the trick (.NET 4.0 users can use WPF Shell Extension google — Microsoft.Windows.Shell or Nicholas Solution).
In the Code Behind you can implement the handlers like this:
In the beginning I was also having a bit of trouble figuring out how this works so I wanted to post a better explanation of what is actually going on.
According to my research the best way to handle things like this is using the Command Bindings. What happens is a «Message» is broadcast to everything in the program. So what you have to do is use the CommandBinding . What this essentially does is say «When you hear this Message do this».
So in the Question the User is trying to Close the Window. The first thing we need to do is setup our Functions that will be called when the SystemCommand.CloseWindowCommand is broadcast. Optionally you can assign a Function that determines if the Command should be executed. An example would be closing a Form and checking if the User has saved.
MainWindow.xaml.cs (Or other Code-Behind)
Now we need to setup the «Connection» between the SystemCommands.CloseWindowCommand and the CloseApp and CloseAppCanExecute
MainWindow.xaml (Or anything that implements CommandBindings)
You can omit the CanExecute if you know that the Command should be able to always be executed Save might be a good example depending on the Application. Here is a Example:
Finally you need to tell the UIElement to send out the CloseWindowCommand.
Its actually a very simple thing to do, just setup the link between the Command and the actual Function to Execute then tell the Control to send out the Command to the rest of your program saying «Ok everyone run your Functions for the Command CloseWindowCommand».
This is actually a very nice way of handing this because, you can reuse the Executed Function all over without having a wrapper like you would with say WinForms (using a ClickEvent and calling a function within the Event Function) like:
In WPF you attach the Function to a Command and tell the UIElement to execute the Function attached to the Command instead.
How to prevent auto-closing of console after the execution of batch file
What command can I put at the end of a batch file to prevent auto-closing of the console after the execution of the file?
17 Answers 17
In Windows/DOS batch files:
This prints a nice «Press any key to continue . . . » message
Or, if you don’t want the «Press any key to continue . . .» message, do this instead:
Depends on the exact question!
Normally pause does the job within a .bat file.
If you want cmd.exe not to close to be able to remain typing, use cmd /k command at the end of the file.
If you want cmd.exe to not close, and able to continue to type, use cmd /k
Just felt the need to clarify what /k does (from windows website):
/k : Carries out the command specified by string and continues.
So cmd /k without follow up command at the end of bat file will just keep cmd.exe window open for further use.
On the other hand pause at the end of a batch file will simply pause the process and terminate cmd.exe on first button press
If you are using Maven and you want to skip the typing and prevent the console from close to see the result you need to use the CALL command in the script, besides just the ‘mvn clean install’.
Like this will close the console
Like this the console will stay open
If you dont use the CALL command neither of the pasts exemples will work. Because for some reason the default behaviour of cmd when calling another batch file (which mvn is in this case) is to essentially replace the current process with it, unlike calling an .exe
WPF MVVM: How to close a window
I have a Button that closes my window when it’s clicked:
That’s fine until I add a Command to the Button i.e.
Now it doesn’t close presumably because I am handling the Command . I can fix this by putting an EventHandler in and calling this.Close() i.e.
but now I have code in my code behind i.e. the method SaveCommand . I am using the MVVM pattern and SaveCommand is the only code in my code behind.
How can I do this differently so as not to use code behind?
21 Answers 21
I just completed a blog post on this very topic. In a nutshell, add an Action property to your ViewModel with get and set accessors. Then define the Action from your View constructor. Finally, invoke your action in the bound command that should close the window.
In the ViewModel:
and in the View constructor:
Finally, in whatever bound command that should close the window, we can simply invoke
This worked for me, seemed like a fairly elegant solution, and saved me a bunch of coding.
Very clean and MVVM way is to use InteractionTrigger and CallMethodAction defined in Microsoft.Interactivity.Core
You will need to add a new namespace as below
You will need the Microsoft.Xmal.Behaviours.Wpf assembly and then the below xaml code will work.
You don’t need any code behind or anything else and can also call any other method of Window .
As someone commented, the code I have posted is not MVVM friendly, how about the second solution?
1st, not MVVM solution (I will not delete this as a reference)
2nd, probably better solution: Using attached behaviours
Behaviour Class Something similar to this:
I’d personally use a behaviour to do this sort of thing:
You can then attach this to your Window and Button to do the work:
I’ve added Command and CommandParameter here so you can run a command before the Window closes.
For small apps, I use my own Application Controller for showing, closing and disposing windows and DataContexts. It’s a central point in UI of an application.
It’s something like this:
and their invocations from ViewModels:
Of course you can find some restrictions in my solution. Again: I use it for small projects, and it’s enough. If you’re interested, I can post full code here or somewhere else/
I’ve tried to resolve this issue in some generic, MVVM way, but I always find that I end up unnecessary complex logic. To achieve close behavior I have made an exception from the rule of no code behind and resorted to simply using good ol’ events in code behind:
Although I wish this would be better supported using commands/MVVM, I simply think that there is no simpler and more clear solution than using events.
I use the Publish Subscribe pattern for complicated class-dependencies:
ViewModel:
Window:
You can leverage Bizmonger.Patterns to get the MessageBus.
MessageBus
Subscription
There is a useful behavior for this task which doesn’t break MVVM, a Behavior, introduced with Expression Blend 3, to allow the View to hook into commands defined completely within the ViewModel.
This behavior demonstrates a simple technique for allowing the ViewModel to manage the closing events of the View in a Model-View-ViewModel application.
This allows you to hook up a behavior in your View (UserControl) which will provide control over the control’s Window, allowing the ViewModel to control whether the window can be closed via standard ICommands.
I struggled with this topic for some time, and eventually went with the simplest approach that is still consistent with MVVM: Have the button execute the Command that does all the heavy lifting and have the button’s Click handler close the window.
XAML
XAML.cs
SaveCommand.cs
True, there is still code-behind, but there isn’t anything inherently bad about that. And it makes the most sense to me, from an OO perspective, to just tell the window to close itself.
We have the name property in the .xaml definition:
Then we have the button:
Then in the ViewModel:
Then at last, the action method:
I used this code to close a pop-up window from an application..
I found myself having to do this on a WPF application based on .Net Core 3.0, where unfortunately behaviour support was not yet officially available in the Microsoft.Xaml.Behaviors.Wpf NuGet package.
Instead, I went with a solution that made use of the Façade design pattern.
Standard command property on the view model:
Because the Close() method is already implemented by the Window class, applying the façade interface to the window is the only required code behind in the UI layer (for this simple example). The command in the presentation layer avoids any dependencies on the view/UI layer as it has no idea what it is talking to when it calls the Close method on the façade.