Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

c# - unable to read another application's caption

Jumping of how i will find windows handle in my main program...

in C#

I run notepad.exe then type something in it,then find the main window handle using SPY++ (0x111111) ,and

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]

internal static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder lpString, int nMaxCount);
.
.
.
GetWindowText((IntPtr)(0x111111), str, 1024);

this code works fine and return me the caption of the main window.

: : but when i do the same to find caption of the child of notepad.exe it just set str to nothing. the spy++ told me that the child's caption has value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The GetWindowText function documentation clearly states that "GetWindowText cannot retrieve the text of a control in another application. ... To retrieve the text of a control in another process, send a WM_GETTEXT message directly instead of calling GetWindowText."

You can retrieve the control's text with the following code:

[DllImport("user32.dll", EntryPoint = "SendMessage")]
public static extern IntPtr SendMessageGetText(IntPtr hWnd, uint msg, UIntPtr wParam, StringBuilder lParam);

const uint WM_GETTEXT = 13;
const int bufferSize = 1000; // adjust as necessary
StringBuilder sb = new StringBuilder(bufferSize);
SendMessageGetText(hWnd, WM_GETTEXT, new UIntPtr(bufferSize), sb);
string controlText = sb.ToString();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...