I am able to get top active window (title) in my code but I wanted to know how to get all the children(content and controls or elements -image, link, button etc) inside the active top window in my code. I searched many links such as - Retrieve all the controls of any window with their types and value which suggests- To enumerate top level windows use EnumWindows(), to get their child windows use EnumChildWindows(). But I am not able to understand how to implement it in my code and get the children of top active windows which is focused.
It would be great if someone helped me around with some sample code. Stuck from long time exploring and checking different links.
Below is the code which gives me top active window title and displaying in the grid.
xaml code -
<Grid x:Name="grid">
</Grid>
.cs Class code -
public partial class MainWindow : Window
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
private static IntPtr GetActiveWindow()
{
IntPtr handle = IntPtr.Zero;
return GetForegroundWindow();
}
[DllImport("user32.dll", EntryPoint = "GetWindowTextW", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
ListBox lst = new ListBox();
public MainWindow()
{
InitializeComponent();
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(DispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
dispatcherTimer.Start();
var d = ActiveWindowTitle();
var t = GetForegroundWindow();
grid.Children.Add(lst);
}
public static IntPtr GetTopWindow(string wClass, string wCaption)
{
if (string.IsNullOrEmpty(string.Concat(wClass, wCaption)))
{
return (IntPtr)0;
}
return (IntPtr)0;
}
private void DispatcherTimer_Tick(object sender, EventArgs e)
{
string title = ActiveWindowTitle();
var current = this.Title;
if (!current.Equals(title) && !String.IsNullOrEmpty(title))
lst.Items.Add("Title: " + title );
}
private string ActiveWindowTitle()
{
const int nChar = 256;
StringBuilder ss = new StringBuilder(nChar);
IntPtr handle = IntPtr.Zero;
handle = GetForegroundWindow();
if (GetWindowText(handle, ss, nChar) > 0)
return ss.ToString();
else return "";
}
}