初识 Windows 消息机制——C语言调用计算器-LMLPHP ZZ.zip  



M.C
  1. #include <windows.h>
  2. #include <WinUser.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>

  5. int main(){

  6.     BOOL opened; // 计算器是否已经成功打开的标志
  7.     STARTUPINFO si ={sizeof(si)}; // 计算器启动信息
  8.     PROCESS_INFORMATION pi; // 计算器进程信息
  9.     HWND h1 = NULL; // 计算器窗口指针
  10.     int i=0;
  11.     BOOL postMsgResult;



  12.     // 打开计算器
  13.     opened = CreateProcess(NULL, "calc.exe", NULL, NULL, FALSE, 0, NULL,NULL, &si, &pi);
  14.     if ( !opened ) {
  15.         printf("无法打开计算器,错误码 = %d\n", GetLastError());
  16.         return;
  17.     }

  18.     // 找到该窗口
  19.     while ( h1 == NULL && i < 3 ){
  20.          h1 = FindWindow(NULL, "计算器");
  21.          if ( h1 == NULL ) {
  22.             i ++;
  23.             Sleep(1000);
  24.          }
  25.     }
  26.     if ( h1 == NULL ) {
  27.         printf("找不到已经打开的计算器,错误码 = %d\n", GetLastError());
  28.         return;
  29.     }
  30.     for(i = 0; i < 3; i++){
  31.         // keybd_event(0x39,0,KEYEVENTF_KEYUP,0); // FIXME
  32.         // msgResult = SendMessage(h1,WM_CHAR,'4',0); // FIXME
  33.         SetLastError(0);
  34.        postMsgResult = PostMessage(h1,WM_CHAR,'1'+i,0);
  35.         if ( i < 2 ){
  36.             PostMessage(h1,WM_CHAR,'+',0);
  37.         } else {
  38.             PostMessage(h1,WM_CHAR,'=',0);
  39.         }
  40.         printf("result=%d, error=%d\n", postMsgResult, GetLastError());
  41.         Sleep(1000);
  42.     }

  43.     system("Pause");
  44.     return 0;
  45. }

11-08 05:09