Luthgers, John
8/15/2008 5:28:00 PM
Matthias, yes, you are right. I've done something wrong with the marshaling
type and thats the reason why it wasnt working in my previous tests.
Alex, here is the code to get the title of the current selected top levels
screen. You need:
- a form
- a enabled timer
- a text box called textbox1
- a text box called textbox2
- wire the Tick-Event of timer1 to timer1_Tick
Its very easy to extend the example for child windows. Just use the
GetWindow (GW_CHILD / GW_HWNDNEXT) to iterate through all childs, subchilds
and so on. At the end you should move the instantiation of StingBuilder to
e.g. the constructor or something else, so that the object is created only
once and reused all the time.
I hope this helps.
-J-
<code>
private void timer1_Tick(object sender, EventArgs e)
{
IntPtr wnd = GetForegroundWindow();
textBox1.Text = wnd.ToInt32().ToString();
StringBuilder text = new StringBuilder(2000);
SendMessage(wnd, WM_GETTEXT, new IntPtr(2000), text);
textBox2.Text = text.ToString();
}
/// <summary>
/// The GetForegroundWindow function returns a handle to the foreground
window.
/// </summary>
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder lParam);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
enum GetWindow_Cmd : uint
{
GW_HWNDFIRST = 0,
GW_HWNDLAST = 1,
GW_HWNDNEXT = 2,
GW_HWNDPREV = 3,
GW_OWNER = 4,
GW_CHILD = 5,
GW_ENABLEDPOPUP = 6
}
const int WM_GETTEXT = 0xD;
</code>