【问题标题】:how to send a message from one windows console application to another?如何将消息从一个 Windows 控制台应用程序发送到另一个?
【发布时间】:2013-11-30 12:20:32
【问题描述】:

我有一个启动子进程的 Windows 控制台应用程序。 如何向子进程发送消息? 我找到了像PostMessage()/PeekMessage() 这样的函数——这就是我需要的,但据我所知,它在一个应用程序中使用,并使用 HWND 来识别目标窗口(我在应用程序中没有窗口)。 此外,我还阅读了有关 ipc 的材料,例如命名管道也需要 HWND。 我想要这样的东西:

[program 1]

int main()
{
    CreateProcess(.., processInfo);
    SendMessage(processId, message);
}

[program 2]

int main()
{
    while(1)
    {
//      do thw work
        Sleep(5 * 1000);
//      check message
        if(PeekMessage(message,..))
        {
        break;
        }
    }
}

子进程需要得到消息,它应该完成它的工作,而不是立即终止,而是完成当前的迭代。这就是为什么我不使用信号并且阻止“接收消息”也不合适的原因。

【问题讨论】:

  • 已经找到 PostThreadMessage(),它有帮助!谢谢;)

标签: c++ winapi ipc windows-messages


【解决方案1】:
[program 1]
int main()
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    std::string path = "c:\\program2.exe";
    CreateProcess(path.c_str(), .. , &si, &pi ) ) 
    Sleep(12 * 1000); // let program2 do some work
    PostThreadMessage(pi.dwThreadId, 100, 0, 0);
}

[program 2]
int main(int argc, char * argv[])
{
    MSG message;
    for(int i = 0; i < 1000; i++)
    {
        std::cout << "working" << std::endl;
        Sleep(2 * 1000);
        if(PeekMessage(&message, NULL, 0, 0, PM_NOREMOVE))
        {
            break;
        }
    }
}

【讨论】:

    【解决方案2】:

    尝试创建Message-Only Window

    这是一个仅用于发送和接收消息的窗口。您可以通过将HWND_MESSAGE 指定为窗口父级来创建它。

    【讨论】:

      【解决方案3】:

      在程序 1 中,您应该使用 FindWindow 函数来获取程序 2 的句柄

      然后使用 SendMessage 函数

      [节目1]

          int main()
          {
           HWND hwnd=FindWindow(NULL,formText);//formText name of program 2
              if(hwnd!=0)
              {
                  COPYDATASTRUCT cd;
              cd.dwData = 100;
              cd.cbData = 100;
              cd.lpData = msg;                //msg additional data
              SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM)(&cd));
              }
          }
      
      [program 2]
      
          void handlemessage(MSG *msg)
          {
              //handle
          }
      
      
          int main()
         {
      
              MSG msg;
              while (GetMessage(&msg, NULL, 0, 0))
              {
                 handlemessage(&msg);
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2013-09-15
        • 2016-07-02
        • 1970-01-01
        • 2010-10-03
        • 1970-01-01
        • 2013-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多