What is an alternative to Sendkeys for closing a legacy application?
I want my C# program to shut down a certain legacy application before proceeding. The legacy app may be shut down immediately using ctrl+x. I could do this using S开发者_开发知识库endkeys, but I've been told that sendkeys can be a little flaky. Is there an alternative way for me to send this key combination and shut the legacy app down?
If you know what the window's title is on the caption bar, such as 'Foo', then you can use p/invoke to find the window and get the handle from it 'FindWindow'. Once you get the handle, then you can use 'SendMessage' to that handle sending a 'WM_KEYUP' that denotes Ctrl+X together.
Hope this helps, Best regards, Tom.
If this is a GUI application. It may also respond to Alt+F4 via SendKeys.
Unlike ctrl+x, Alt+F4 will not depend on which window has focus. This is a standard accelerator for windows applications and most older GUI applications will support it. The main reason SendKey is considered flakey is because keystrokes get delivered to the focus window, which may or may not understand them. But Alt+F4 is an accelerator, so it should work regardless of which window has focus.
If you can get the handle to the main window. (use FindWindow
if you don't have it already). You can
PostMessage(hwndApp, WM_SYSCOMMAND, SC_CLOSE, 0);
This is equivalent to choosing the close option from the system menu on the window. SendMessage
should work as well, but PostMessage is safer since your application doesn't wait for the message to be delivered.
WM_SYSCOMMAND
Other options include:
System.Diagnostics.Process.Kill
System.Diagnostics.Process.CloseMainWindow
If the latter works, use it. If not, and you lose nothing by killing the process directly, then Kill().
精彩评论