If the target window is owned by the current process, GetWindowText causes a WM_GETTEXT message to be sent to the specified window or control. If the target window is owned by another process and has a caption, GetWindowText retrieves the window caption text. If the window does not have a caption, the return value is a null string. This behavior is by design. It allows applications to call GetWindowText without becoming unresponsive if the process that owns the target window is not responding. However, if the target window is not responding and it belongs to the calling application, GetWindowText will cause the calling application to become unresponsive.

To retrieve the text of a control in another process, send a WM_GETTEXT message directly instead of calling GetWindowText.

# GetWindowText是怎么工作的

1. 如果你要拿标题的窗口属于当前的进程，那么GetWindowText就是发送WM_GETTEXT消息过去，然后获取标题。
2. 如果你要拿标题的窗口不属于当前的进程，那么GetWindowText就不发送WM_GETTEXT消息，而是直接从一个特定的地方读取标题。

# GetWindowText为什么这么实现

1. 让系统来处理，WM_NCCREATE消息会把CreateWindow/Ex的参数lpWindowName放到一个特定位置。处理WM_GETTEXT消息是就把这个特定位置存储的字符串返回出去。处理WM_SETTEXT消息就是把传进来的字符串放到那个特定位置。
2. 窗口自己处理，自己决定如何响应WM_GETTEXTWM_SETTEXT消息。

# GetWindow带来的坑

The EnumChildWindows function is more reliable than calling GetWindow in a loop. An application that calls GetWindow to perform this task risks being caught in an infinite loop or referencing a handle to a window that has been destroyed.

# 如何绕过这些坑

1. 遍历窗口要使用EnumWindows或者EnumChildWindows
2. 如果我们不希望调用GetWindowText的线程挂起，需要做超时处理。
3. 大部分情况下我们获取窗口标题并不需要处理当前进程的窗口，所以在调用GetWindowText之前可以做个判断，如果是当前进程就直接返回。如果我们只需要获取某些特定进程的窗口标题，可以在调用GetWindowText之前判断目标窗口是否属于我们感兴趣的进程。