how to get current application windows title?
-
hi every one, I want to get current application windows title and then show it? through my search,I find out that I should use getforegroundWindow(),but I don't get it how to do that ? I'd appreciate any help.
To use C++ functions you need to do some research into P/Invoke. Here's how to declare the functions you need in C#:
// NativeMethods.cs
using System;
using System.Text;
using System.Runtime.InteropServices;namespace ConsoleApplicationTest
{
internal static class NativeMethods
{
[DllImport("User32.dll")]
public static extern IntPtr GetForegroundWindow();\[DllImport("User32.dll")\] public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); }
}
Usage example:
// Program.cs
using System;
using System.Text;namespace ConsoleApplicationTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press any key to get text");
Console.ReadKey();
IntPtr handle = NativeMethods.GetForegroundWindow();
if (handle != IntPtr.Zero)
{
StringBuilder builder = new StringBuilder(255);
NativeMethods.GetWindowText(handle, builder, builder.Capacity);
Console.WriteLine(builder.ToString());
}
Console.ReadKey();
}
}
}I have used a hardcoded max length of 255. You can use GetWindowText[^] to get the length of the text before getting the text so you won;t be wasting memory with your string builder or risk truncating if it's longer than you expect. I'll leave implementing that (which is simple) as an exercise for you.
Dave
Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)