C# how to use WM_GETTEXT / GetWindowText API / Window Title

后端 未结 3 2011
渐次进展
渐次进展 2020-12-03 05:12

I want to get the content of the control / handle of an application..

Here\'s the experimental code..

 Process[] processes = Process.GetProcessesByNa         


        
相关标签:
3条回答
  • 2020-12-03 05:41

    GetWindowText won't give you the content of edit windows from other applications - it only supports default-managed text [like the captions of labels] across processes to prevent hangs... you'll have to send WM_GETTEXT.

    You'll need to use a StringBuilder version of SendMessage:

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, [Out] StringBuilder lParam);
    
    const int WM_GETTEXT = 0xD;
    StringBuilder sb = new StringBuilder(65535);
    // needs to be big enough for the whole text
    SendMessage(hWnd_of_Notepad_Editor, WM_GETTEXT, sb.Length, sb);
    
    0 讨论(0)
  • Have a look at http://pinvoke.net/default.aspx/user32/GetWindowText.html and also the documentation on MSDN. Below you find a short code example how to use the GetWindowText method.

    0 讨论(0)
  • 2020-12-03 05:44
    public class GetTextTestClass{
    
        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        public static extern bool SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam);
    
        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr SendMessage(int hWnd, int Msg, int wparam, int lparam);
    
        const int WM_GETTEXT       = 0x000D;
        const int WM_GETTEXTLENGTH = 0x000E;
    
        public string GetControlText(IntPtr hWnd){
    
            // Get the size of the string required to hold the window title (including trailing null.) 
            Int32 titleSize = SendMessage((int)hWnd, WM_GETTEXTLENGTH, 0, 0).ToInt32();
    
            // If titleSize is 0, there is no title so return an empty string (or null)
            if (titleSize == 0)
                return String.Empty;
    
            StringBuilder title = new StringBuilder(titleSize + 1);
    
            SendMessage(hWnd, (int)WM_GETTEXT, title.Capacity, title);
    
            return title.ToString();
        }
    }
    
    0 讨论(0)
提交回复
热议问题