Geeks With Blogs
Rupreet's Weblog Looking deep inside under the hood

Recently I was working on a utility very similar spy++, but could do more than what we have in spy++ - like besides getting me the window (not Windows :P) class name and its height/width etc, it could also give me the caption of the window. I read couple of articles and all suggested to use global hooks. Using hooks because we are doing all this stuff using mouse – a very similar UI experience like that of spy++ - you click on the bull’s eye icon and drag the mouse to the destination window, it’ll give you all the details. If we read MSDN about hooks, the very first thing they say is that they are pretty expensive. Of course, it will be expensive; we are adding another function to be processed before the message reaches its destination. When I started working on it, I simply had some P/Invoke definitions and handled Mouse Down and Mouse Up events and it worked! Just simple .NET event handling and some P/Invokes, you are done! In my Mouse Down event, I set my cursor icon to Bull’s eye and other UI effectsJ. In Mouse Up, we get the cursor position, get the window handle by using WindowFromPoint(Point p) API defined in user32.dll. Once you get the window handle, you can get all kind of window details like the window class name, window height, width etc using APIs defined in user32.dll. Then I tried to get the caption of the window – and that also was simple 2 line code. I used SendMessage API again defined in user32.dll and passed WM_GETTEXT (value of WM_GETTEXT is defined in winuser.h file) in the message parameter of this API. Here are the signatures of the same



static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, [Out] StringBuilder lParam);


In first parameter, pass the handle of the window whose caption you are looking for, second parameter is your message ID – in this case, its WM_GETTEXT, third parameter is the length of the string it should read, and fourth parameter which is an out parameter, is the buffer where the caption text will be copied and we can read it from here.


If you want to have a look at this utility, email me and I’ll send it across.


So without using any hooks, we got window caption and class name – simple isn’t it?

Posted on Monday, October 17, 2005 8:28 PM C# , .NET Framework | Back to top

Comments on this post: Getting window caption and class name

# re: Getting window caption and class name
Requesting Gravatar...
I wrote a similar example if you were interested in checking it out. I'd enjoy seeing your app too. Always looking for similar articles!

Here's a link to my article.

You notify me on my website if you'd be interested in sharing source.

Left by Mark (Code6) Belles on Apr 03, 2006 7:34 AM

Your comment:
 (will show your gravatar)

Copyright © Rupreet Singh Gujral | Powered by: