how to send a message from one windows console application to another?

我只是一个虾纸丫 提交于 2019-12-04 23:43:25

问题


I have a windows console application which starts child process. How can I send a message to child process? I found functions like PostMessage()/PeekMessage() - that's what I need, but as I understand, it is used inside one application, and uses HWND to identify the target window (I have no windows in application). Also I've read materials about ipc, for example named pipes demand HWND too. I want something like that:

[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;
        }
    }
}

Child process needs to get message that it should finish its work, not terminate immediately, but finish current iteration. That's why I don't use signals and blocking 'receive message' is not appropriate too.


回答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:


Try creating a Message-Only Window.

This is a window which is only used for sending and receiving messages. You can create it by specifying HWND_MESSAGE as the window parent.




回答3:


In program 1 you should use the FindWindow function to get handle of program 2

and then use SendMessage function

[program 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);
        }
    }


来源:https://stackoverflow.com/questions/20029338/how-to-send-a-message-from-one-windows-console-application-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!