How do I get the title of the current active window using c#?
See example on how you can do this with full source code here:
http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
Edited with @Doug McClean comments for better correctness.
c# - Get current window title
Can you stick it in a loop on another thread. Have two variables: previousWindow and currentWindow. Keep comparing them, when they change - you update your log file.
How to get active window that is not part of my application?
Check this code:
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
C# get information about current active window
I think you want "GetWindowModuleFileName()" instead of GetWindowText
You pass in the hwnd, so you'll still need the call to GetForegroundWindow()
Get active window information using C# on Mac
You are looking for the FrontmostApplication
of the shared NSWorkspace
, it returns a NSRunningApplication
instance.
var foreground_app = NSWorkspace.SharedWorkspace.FrontmostApplication;
Console.WriteLine($"Name: {foreground_app.LocalizedName}");
Console.WriteLine($"Pid: {foreground_app.ProcessIdentifier}");
re: https://developer.apple.com/documentation/appkit/nsrunningapplication?language=objc
get the titles of all open windows
Something like this:
using System.Diagnostics;
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (!String.IsNullOrEmpty(process.MainWindowTitle))
{
Console.WriteLine("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);
}
}
Related Topics
Is Int[] a Reference Type or a Value Type
What Is the C# Equivalent of Friend
Can You Catch a Native Exception in C# Code
Referencing a Variable from Another Method
How to Add an Item to a Ienumerable<T> Collection
How to Convert a Gi-Normous Integer (In String Format) to Hex Format? (C#)
Using Linq to Concatenate Strings
Cursor.Current VS. This.Cursor
Regular Expression to Remove HTML Tags
Is There a .Net/C# Wrapper for SQLite
Add Data Annotations to a Class Generated by Entity Framework
How to Get a Property Value Based on the Name