Knowledge Base Nr: 00221 sendkeytoproc.cpp - http://www.swe-kaiser.de

Downloads:

WIN32: simulierte tastendrücke an prozess schicken. prozess wird über den namen ausgewählt

  
//beispielaufruf: schreibt 'lulli' in eine gestartete notepad-applikation
SendKeyToProcess("notepad.exe", "L#U#L#L#I#SPACE#");

CProcessSupport g_proc;
HWND g_hwnd = 0;

BOOL CALLBACK EnumChildProc(HWND hwndChild, LPARAM lParam)
{
DWORD dwFindProcessId = (DWORD)lParam;
DWORD dwProcessId = 0;
DWORD dwThId = ::GetWindowThreadProcessId(hwndChild, &dwProcessId);
TRACE("EnumChildProc hwndChild = %d dwProcessId=%d\n", hwndChild, dwProcessId);
if (dwProcessId == dwFindProcessId)
{
g_hwnd = hwndChild;
return FALSE;
}
return TRUE;
}

void SendKeyToProcess(const char* lpszProcessname, const char* lpszKeys)
{
HANDLE ss = CSystemExt::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (ss == INVALID_HANDLE_VALUE)
return;

PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);

DWORD dwFindProcessId = 0;
bool bFound = false;
BOOL bSucc = CSystemExt::Process32First(ss, &pe);
for (/**/; bSucc; bSucc = ::Process32Next(ss, &pe))
{
TRACE("Process32Next %04d\t%s\n", pe.th32ProcessID, pe.szExeFile);
if (stricmp(lpszProcessname, pe.szExeFile) == 0)
{
dwFindProcessId = pe.th32ProcessID;
bFound = true;
break;
}
}

::CloseHandle(ss);

g_hwnd = 0;
EnumWindows(EnumChildProc, (LPARAM) dwFindProcessId);

if (g_hwnd)
{
HWND orgHwndNormal = 0;
HWND orgHwnd = 0;
orgHwndNormal = ::GetFocus();
if (orgHwndNormal)
{
::SetFocus(g_hwnd);
}

orgHwnd = ::GetForegroundWindow();
::SetForegroundWindow(g_hwnd);

Sleep(10);
int nErr = g_proc.DoKeysPress(lpszKeys, 1);

if (orgHwndNormal)
::SetFocus(orgHwndNormal);

if (orgHwnd)
::SetForegroundWindow(orgHwnd);
}
}