首页 文章

使用user32.dll从外部应用程序的文本框(Unicode)中将文本提取到C#应用程序中

提问于
浏览
0

我在C#中开发了一个应用程序,它从外部应用程序的文本框中提取文本,我使用的是user32.dll,应用程序工作正常,但我的问题是这个 - 外部应用程序的文本框包含unicode格式的文本,所以每当我在我的文本中提取文本应用程序显示“??????”文本 . 我尝试过设置charset.unicode,还使用RichTextBox在我的应用程序中显示文本 . 请告诉我如何从外部应用程序中提取unicode文本 .

这是我正在使用的代码

private void button1_Click(object sender, EventArgs e)
    { IntPtr MytestHandle = new IntPtr(0x00060342);

        HandleRef hrefHWndTarget = new HandleRef(null, MytestHandle);

     // encode text into 
        richTextBox1.Text = ModApi.GetText(hrefHWndTarget.Handle);
     }

public static class ModApi {
[DllImport("user32.dll",EntryPoint = "SendMessageTimeout",SetLastError = true,CharSet = CharSet.Unicode)] public static extern uint SendMessageTimeoutText(IntPtr hWnd,int Msg,int countOfChars,StringBuilder text,uint flags,uint uTImeoutj,uint result);

public static string GetText(IntPtr hwnd)
        {
            var text = new StringBuilder(1024);

            if (SendMessageTimeoutText(hwnd, 0xd, 1024, text, 0x2, 1000, 0) != 0)
            {
                return text.ToString();
            }

            MessageBox.Show(text.ToString());
            return "";
        }
    }

1 回答

  • 0

    你使用WN_GETTEXT不正确阅读文档:http://msdn.microsoft.com/en-us/library/windows/desktop/ms632627%28v=vs.85%29.aspx

    wParam
    
    The maximum number of characters to be copied, including the terminating null character.
    

    或使用正确的功能:http://www.pinvoke.net/default.aspx/user32/GetWindowText.html

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, [Out] StringBuilder lParam);
    
    public static string GetWindowTextRaw(IntPtr hwnd)
    {
        // Allocate correct string length first
        int length = (int)SendMessage(hwnd, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
        StringBuilder sb = new StringBuilder(length + 1);
        SendMessage(hwnd, WM_GETTEXT, (IntPtr)sb.Capacity, sb);
        return sb.ToString();
    }
    

    使其适应SendMessageTimeOut

相关问题