终于解决了C语言控制cmd窗口,多次发送字符串给cmd执行命令,特此记录一下。
功能1:C语言用线程打开记事本,发送消息给记事本,实现向记事本写入字符
功能2:C语言发送消息给已经打开的cmd窗口,实现自动化执行cmd命令,这里是可以持续不断的发送命令,而不是普通的带参数打开cmd,比如一个命令开始,还可以再传递一个结束的命令,等等。
在VS里新建空白cpp工程,设置字符集为多字节,关闭SDL安全检查,新建一个cpp源文件
代码如下:
#include <windows.h>#include <tchar.h>#include <stdio.h>int main(int argc, char* argv[]){TCHAR szCommandLine[] = TEXT("Notepad");//或者WCHAR//LPWSTR szCommandLine = TEXT("NOTEPAD");//错误//STARTUPINFO si = { sizeof(si) };STARTUPINFO si;PROCESS_INFORMATION pi;ZeroMemory(&si, sizeof(si));si.cb = sizeof(si);ZeroMemory(&pi, sizeof(pi));si.dwFlags = STARTF_USESHOWWINDOW; // 指定wShowWindow成员有效si.wShowWindow = TRUE;// 此成员设为TRUE的话则显示新建进程的主窗口,// 为FALSE的话则不显示BOOL bRet = ::CreateProcess(NULL, // 不在此指定可执行文件的文件名szCommandLine,// 命令行参数NULL, // 默认进程安全性NULL, // 默认线程安全性FALSE,// 指定当前进程内的句柄不可以被子进程继承CREATE_NEW_CONSOLE, // 为新进程创建一个新的控制台窗口NULL, // 使用本进程的环境变量NULL, // 使用本进程的驱动器和目录&si,&pi);if (bRet){//WaitForSingleObject(pi.hProcess, INFINITE);// 既然我们不使用两个句柄,最好是立刻将它们关闭::CloseHandle(pi.hThread);::CloseHandle(pi.hProcess);printf(" 新进程的进程ID号:%d \n", pi.dwProcessId);printf(" 新进程的主线程ID号:%d \n", pi.dwThreadId);//TerminateProcess(pi.hProcess, 0);Sleep(5000);//此行是获取已经打开的cmd窗口,并给它发送字符串HWND hcmdwindow = FindWindow("ConsoleWindowClass", "命令提示符");char *cmdstr = "ipconfig";int strcount = strlen(cmdstr);for (size_t i = 0; i < strcount; i++){SendMessage(hcmdwindow, WM_CHAR, (WPARAM)cmdstr[i], (LPARAM)1);}PostMessage(hcmdwindow, WM_KEYDOWN, VK_RETURN, 1);HWND hmyapp = FindWindow("Notepad", NULL);HWND hmyappedit1 = FindWindowEx(hmyapp, NULL, "Edit", NULL);if (hmyappedit1){printf("已找到记事本窗口,它的ID是%0x\n", hmyappedit1);char *str = "ipconfig";int count = strlen(str);for (size_t i = 0; i < count; i++){SendMessage(hmyappedit1, WM_CHAR, (WPARAM)str[i], (LPARAM)1);}PostMessage(hmyappedit1, WM_KEYDOWN, VK_RETURN, 1);}else{printf("未没找到记事本文件\n");}}system("pause");return 0;}/*HWND hmyapp = FindWindow(NULL,"控制cmd程序");HWND hmyappedit = FindWindowEx(hmyapp, NULL , "Edit", NULL);SendMessage(hmyappedit, WM_SETTEXT, NULL, (LPARAM)"HELLO");SendMessage(hmyappedit, WM_CHAR, (WPARAM)'9', (LPARAM)2);HWND hmyapp1 = FindWindow("Notepad", NULL);HWND hmyappedit1 = FindWindowEx(hmyapp1, NULL, "Edit", NULL);SendMessage(hmyappedit1, WM_CHAR, (WPARAM)'9', (LPARAM)2);HWND hmyapp2 = FindWindow("ConsoleWindowClass", "命令提示符");//HWND hmyappedit2 = FindWindowEx(hmyapp1, NULL, "Edit", NULL);//SendMessage(hmyapp2, WM_CHAR, (WPARAM)'9', (LPARAM)1);//SendMessage(hmyapp2, WM_CHAR, (WPARAM)'8', (LPARAM)1);//PostMessage(hmyapp2,WM_KEYDOWN, VK_RETURN, 1);//SendMessage(hmyapp2, WM_CHAR, (WPARAM)'8', (LPARAM)1);char *str = "ipconfig";int count = strlen(str);for (size_t i = 0; i < count; i++){SendMessage(hmyapp2, WM_CHAR, (WPARAM)str[i], (LPARAM)1);}PostMessage(hmyapp2, WM_KEYDOWN, VK_RETURN, 1);char str1[100];scanf_s("%s",str1);printf("%d",strlen(str1));*//*for (size_t i = 0; i < strlen(str); i++){SendMessage(hmyapp2, WM_CHAR, (WPARAM)str1[i], (LPARAM)1);}PostMessage(hmyapp2, WM_KEYDOWN, VK_RETURN, 1);*/
最后达到的效果如下: