天天看點

Windows擷取其他程序中Edit控件的内容

最近做的MFC項目中,有個擷取其他程序中Edit控件内容的需求,本來以為是個很簡單的問題,但是來來回回折騰了不少時間,發博記錄一下。

  剛開始拿到這個問題,很自然的就想到GetDlgItemText():

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()

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.

  描述裡面很清楚寫着不能對其他程式使用,又一次失敗。

  PS:吐槽一下,為什麼GetDlgItemText()裡面不寫這句話,浪費俺的時間。╮(╯▽╰)╭

解決方法:使用SendMessage()向程序發WM_GETTEXT消息擷取。

  SendMessage(handle,message,Wparam,lparam);

    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()。。。。

轉載于:https://www.cnblogs.com/WinkJie/p/10917385.html