Calling SendMessage (P/Invoke) keeps crashing

前端 未结 3 1171
余生分开走
余生分开走 2021-01-06 07:35

I am having to write an application that communicates with a third-party program (AOL, I\'m sorry. :()

Doing a lot of research I found some ways to do this with P/In

3条回答
  •  醉话见心
    2021-01-06 08:16

    Did you manage to solve the "Attempted to read or write protected memory." error? t0mm13b's answer seems to allocate a StringBuilder whose buffer is one character too small (to accommodate the trailing '\0').

    Here's code that works for me:

    [DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true)]
    private static extern Int32 SendMessageByString(IntPtr wnd, UInt32 msg, Int32 WParam, StringBuilder output);
    const int WM_GETTEXTLENGTH = 0x000e;
    const int WM_GETTEXT = 0x000d;
    
    public static string GetText(IntPtr hWnd)
    {
        int len = SendMessageByString(hWnd, WM_GETTEXTLENGTH, 0, null);
        var sb = new StringBuilder(len + 1);  // +1 is for the trailing '\0'
        SendMessageByString(hWnd, WM_GETTEXT, sb.Capacity, sb);
        return sb.ToString();
    }
    

提交回复
热议问题