最近作的MFC項目中,有個獲取其餘進程中Edit控件內容的需求,原本覺得是個很簡單的問題,可是來來回回折騰了很多時間,發博記錄一下。app
剛開始拿到這個問題,很天然的就想到GetDlgItemText():ide
UINT GetDlgItemText( HWND hDlg, // handle to dialog box int nIDDlgItem, // control identifier LPTSTR lpString, // pointer to buffer for text int nMaxCount // maximum size of string );The GetDlgItemText function retrieves the title or text associated with a control in a dialog box. 調試
看API的描述和要實現的需求同樣,天然就用起來了,可發現無論怎樣這個API始終調用失敗,獲取不到內容。一直覺得是代碼哪裏出問題了,調試很久。後來Google以後在CSDN論壇上找到個老帖,得知這個API只有在Windows 2K以前的系統才能跨進程使用,無奈放棄。進程
因而查了下,還有一個GetWindowText()ci
int GetWindowText( HWND hWnd, // handle to window or control LPTSTR lpString, // text buffer int nMaxCount // maximum number of characters to copy );The GetWindowText function copies the text of the specified window's title bar (if it has one) into a buffer. If the specified window is a control, the text of the control is copied. However, GetWindowTextcannot retrieve the text of a control in another application.string
描述裏面很清楚寫着不能對其餘程序使用,又一次失敗。it
PS:吐槽一下,爲何GetDlgItemText()裏面不寫這句話,浪費俺的時間。╮(╯▽╰)╭io
解決方法:使用SendMessage()向進程發WM_GETTEXT消息獲取。function
SendMessage(handle,message,Wparam,lparam);sso
Handle爲窗口句柄,
message爲消息類型,
wparam和lparam爲消息參數;
WM_GETTEXT
An application sends a WM_GETTEXT message to copy the text that corresponds to a window into a buffer provided by the caller.
其實使用這個消息等於用GetwindowText()。。。。