I want to write a C# program which will launch an .exe (this is an easy job, I know how to do it.) but now I want to add some more fu开发者_JAVA百科nctionality to it. I want to take user inputs to my program and want to pass them to running .exe as a input.Also I want to click on a particular button available on the exe window. Important thing is, I want to do it programatically without user knowledge that we are actually running that exe in background. Please let me know if it is possible. It is very urgent.
Yes it is possible with Windows API. You need to send a message to that Window. At first use Spy++ to get IDs of all buttons you want to click. Spy++ is a Visual Studio tool and it shows you what messages are being sent to the application when you press those buttons. Then use PostMessage() function (Windows API) to send the same message programatically.
You can also for example look at Winamp (a music player for windows), there is documentation on how to press its buttons from external app. You can do it the same way for other apps, you just need to know IDs of all controls and names of windows or their classes.
here is code to click on Winamp's pause button:
#define AMP_PAUSE 40046
HWND hwnd = FindWindow("Winamp v1.x", 0);
if(hwnd) SendMessage(hwnd, WM_COMMAND, AMP_PAUSE, 0);
This is written in C++. If you do it in C#, use PInvoke to get access to Windows API. I assume you know how to do this. In the first step FindWindow gets a handle to the window, it identifies it by the name of its class. Then we use SendMessage or PostMessage to send the message. There are four parameters: window to send the message to, message id, and two parameters.
In Spy++ you can find those parameters you need for FindWindow and SendMessage. Please start it and play with it a little bit to see what it can do.
If you want to avoid directly use of WIN API, there's a small library that can help you with this, WindowScrape.
You can use it directly from C#. Some of the features:
- Search for windows and child controls registered in memory.
- Change the titles of windows
- Change the text of UI elements (permissions/privacy permitting)
- Click on UI elements
- Read the Titles of windows
- Read the text from UI elements
- Navigate through object hierarchies
- Set object locations
- Set object sizes
There might be other similar libraries, but at this point this is the only one that i'm aware.
Edited
Sample Usage:
using System.Windows.Forms;
//WindowScrape
using WindowScrape.Types;
namespace WindowsFormsTestApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var npad = HwndObject.GetWindowByTitle("Untitled - Notepad");
}
}
}
If it is a WPF application you could have a look at AutomationPeers
精彩评论