如何在 C# 中使用 SendMessageTimeout 获取窗口标题 [英] how to get a window title using SendMessageTimeout in C#

查看:50
本文介绍了如何在 C# 中使用 SendMessageTimeout 获取窗口标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要枚举所有打开的窗口并获取它们的标题,但问题是有些窗口属于同一个进程但属于不同的线程,该线程被阻塞(等待互斥锁).因此,我不能将 GetWindowText 用于属于我自己进程的窗口,因为这将导致 SendMessage 调用阻塞我的代码执行(因为它将等待被阻塞线程的 relpy).

I need to enumerate all open windows and get their title, but the problem is that some windows belong to the same process but to a different thread, which is blocked (waiting for a mutex). Therefore I cannot use GetWindowText for windows that belong in my own process as this will result to a SendMessage call which will block my code's execution (as it will be waiting a relpy for the blocked thread).

顺便说一句,这是一篇关于 GetWindowText 内部如何工作的有趣文章:http://blogs.msdn.com/b/oldnewthing/archive/2003/08/21/54675.aspx

Btw here is an interesting article on how the GetWindowText works internally: http://blogs.msdn.com/b/oldnewthing/archive/2003/08/21/54675.aspx

作为一个解决方案,决定对窗口使用 SendMessageTimeout 以检索其标题,但我无法使其工作.我正在做的是:

As a solution decided to use SendMessageTimeout to the window in order to retrieve its title but I can't make it work. What I am doing is:

[DllImport("User32.dll")]
public static extern int SendMessageTimeout(
  IntPtr hWnd, 
  int uMsg, 
  int wParam, 
  int lParam, 
  int fuFlags, 
  int uTimeout, 
  out StringBuilder lpdwResult);

...

StringBuilder sb = new StringBuilder(256);
int result = Win32API.SendMessageTimeout(
  hWnd, 
  0x0D /*WM_GETTEXT*/, 
  256, 
  0, 
  10 /*SMTO_ABORTIFHUNG | SMTO_NOTIMEOUTIFNOTHUNG*/, 
  500, 
  out sb);

但我总是得到 0 表示该函数失败,并且 sb 始终为空.有任何想法吗?非常感谢.

but I always get 0 meaning that the function failed, and sb is always null. Any ideas? Thanks a lot.

推荐答案

您需要在 lParam 中传递字符串缓冲区,而不是在 lpdwResult 中.lpdwResult 可能为 NULL 或输出 Int32,它包含消息处理的结果.请注意,SendMessageTimeout 无助于获取无响应窗口的标题,但可以防止调用方阻塞.

You need to pass string bufer in lParam, and not in lpdwResult. lpdwResult may be NULL or out Int32, it contains result of the message handling. Note that SendMessageTimeout doesn't help to get title of non-responsive window, but prevents caller blocking.

有趣的是,SendMessageTimeout 的 PInvoke 声明取决于您要发送的消息.如果需要在同一个程序中发送不同的消息,我认为可以做多个PInvoke声明调用同一个API.

Interesting point here that PInvoke declaration of SendMessageTimeout depends on the message you want to send. In the case it is necessary to send different messages in the same program, I think it is possible to make several PInvoke declarations calling the same API.

这篇关于如何在 C# 中使用 SendMessageTimeout 获取窗口标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆