將鍵擊發送到另一個應用程序不是一個好的解決方案。有很多潛在的問題,例如C# sendkeys to other application to particular textfield。更好的解決方案是更直接地與其他程序進行交互。它需要對Windows的工作方式有更多的技術理解。其中許多優點之一是,您可以像編寫它一樣輕鬆地閱讀其他應用程序中的文本。
有關示例,請參閱我的Clicking a Button in Another Application,但使用C#。我希望這個解釋至少是有幫助的。可以使用相同的技術將數據放入文本框或文本框中,然後單擊按鈕。 WM_SETTEXT message將用於將數據放入另一個應用程序的文本框中。以下是將文本放入記事本的示例控制檯程序。
#include "stdafx.h"
struct pidandhwnd {
DWORD dwProcessId;
HWND hwnd;
};
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
pidandhwnd *ppnh = (pidandhwnd *)lParam;
DWORD dwProcessId;
GetWindowThreadProcessId(hwnd, &dwProcessId);
if (ppnh->dwProcessId == dwProcessId)
{
ppnh->hwnd = hwnd;
return FALSE;
}
return TRUE;
}
int main()
{
TCHAR szCmdline[] = TEXT("Notepad.exe");
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
BOOL bSuccess = FALSE;
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = NULL;
siStartInfo.hStdOutput = NULL;
siStartInfo.hStdInput = NULL;
LPARAM lParam = NULL;
pidandhwnd pnh;
const int ControlId = 15; // Edit control in Notepad
HWND hEditWnd;
bSuccess = CreateProcess(NULL,
szCmdline, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
if (!bSuccess) {
std::cout << "Process not started\n";
return 0;
}
std::cout << piProcInfo.dwProcessId << " Notepad Process Id\n";
WaitForInputIdle(piProcInfo.hProcess, 1000);
pnh.dwProcessId = piProcInfo.dwProcessId;
pnh.hwnd = NULL;
EnumDesktopWindows(NULL, EnumWindowsProc, (LPARAM)&pnh);
if (pnh.hwnd == NULL)
{
std::cout << "Notepad not found\n";
return 0;
}
//std::cout << "Notepad found\n";
// Get the edit box on Notepad
hEditWnd = GetDlgItem(pnh.hwnd, ControlId);
// Send the text
SendMessage(hEditWnd, WM_SETTEXT, NULL, (LPARAM)_T("This is from somewhere else."));
return 0;
}
應該有幾個例子,告訴你如何做到這一點:http://stackoverflow.com/questions/2113950/how-to-send-keystrokes-to-a-window。如果您需要設置輸入字段的焦點,我確信有辦法做到這一點 – Marged
謝謝!這絕對看起來更好,當我第一次遇到這種情況時,我的印象是,這不適用於所有應用程序。但似乎我錯了。我現在試着去實現它。 此外,我是新來的stackoverflow,我現在做的正確的事情是什麼?關閉這個問題?以某種方式向上推動你? – SledoMalset
@Marged:這要求,目的地確實是一個本地窗口(可通過它的'HWND'訪問)。通常情況並非如此,解決方案將無法工作。記錄和支持的用於自動化UI的解決方案是[UI自動化](https://msdn.microsoft.com/en-us/library/windows/desktop/ee684009.aspx)。 – IInspectable