Send windows message to a Windows Service

前端 未结 7 1942
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 05:57

Is there any tool to send (mimic) a windows message like \'WM_ENDSESSION\' to a windows service?

OR

How can I send a windows message to a process using C#?

7条回答
  •  失恋的感觉
    2021-02-06 06:28

    I would recommend Importing and defining the following:

    [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
    public static extern bool PostMessage(IntPtr handleWnd, UInt32 Msg, Int32 wParam, Int32 lParam);
    
    const int WM_ENDSESSION = 0x0016,
              WM_TRUE = 0x1,
              WM_FALSE = 0x0;
    

    Then send through 0x1 or 0x0 representing true or false as the wParam message.

    So in your code you will use:

    PostMessage(HandleToSendTo, WM_ENDSESSION, WM_TRUE, 0);
    

    Where HandleToSendTo is the Window Handle of the window you would like to send the message to.

    Edit
    To get the windows handle if you don't know it, I'm assuming that you will know it's title or name. If so you can use this:

    [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
            public static extern int FindWindowEx(int hwndParent, int hwndEnfant, int lpClasse, string lpTitre);
    

    Which more information about can be found in this question.

    Or maybe

    I don't know if this is a similar handle, I doubt it, but someone could let me know if it is, but you can get a Process handle, which means you could get the process using Process.GetProcessesByName("MyAppName");, althought don't rely on this as I don't think that it will get the handle that you are after. Just a suggestion.

提交回复
热议问题