Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

winapi - how to programmatically click on a button in running app using C# code

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 functionality 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...