C# :: Aufgabe #45
5 Lösungen

Fensternamen ausgeben
Fortgeschrittener - C#
von Process1
- 15.01.2013 um 06:51 Uhr
Erstelle ein Konsolenprogramm. In der Konsole sollen Fenstertitel & und zugehöriger
Prozessname ausgegeben werden, wenn das Vordergrundfenster wechselt. (Programm soll durchgehend laufen)
Die Konsole selber soll nicht ausgegeben werden.
Der Windows-Explorer soll nicht ausgegeben werden.
Prozessname ausgegeben werden, wenn das Vordergrundfenster wechselt. (Programm soll durchgehend laufen)
Die Konsole selber soll nicht ausgegeben werden.
Der Windows-Explorer soll nicht ausgegeben werden.
Konsolenausgabe:
Fenstername: Windows Task-Manager
Prozessname: taskmgr
Fenstername: Neue Aufgabe erstellen - TRAIN your programmer - Google Chrome
Prozessname: chrome
usw.
Lösungen:
- Das Fenster wird nur aktualisiert wenn sich ein Programmfenster öffnet, schliesst oder der Titel ändert.
- Mit etwas LINQ und Erweiterungsmethoden
- Kleine Erweiterung: Es wird auch die PID (=Process ID) angezeigt um mehrfach geöffnete Programme zu erkennen.
C#-Code
- Mit etwas LINQ und Erweiterungsmethoden
- Kleine Erweiterung: Es wird auch die PID (=Process ID) angezeigt um mehrfach geöffnete Programme zu erkennen.

using System; using System.Collections.Generic; using System.Linq; using System.Diagnostics; using System.Threading; // Lösung Scavanger 2013 namespace ProcessList { class Program { // Hinweis: Programm mit STRG+C beenden. static void Main(string[] args) { ProcessList procList = new ProcessList(new string[] { "explorer" }); Dictionary<string, string> oldProcesses = procList.GetProcesses(); Dictionary<string, string> curProcesses = null; Print(oldProcesses); while (true) { Thread.Sleep(500); curProcesses = procList.GetProcesses(); if (curProcesses.CompareByKeys(oldProcesses)) { Console.Clear(); Print(curProcesses); } oldProcesses = curProcesses; } } private static void Print(Dictionary<string, string> processes) { foreach (KeyValuePair<string, string> process in processes) { Console.WriteLine("Fenstername: {0}", process.Key); Console.WriteLine("Prozessname: {0}{1}", process.Value, Environment.NewLine); } } } /// <summary> /// Listet alle laufenden Prozesse auf die ein Fenster besitzen. (Prozessname, Fenstertitel) /// </summary> public class ProcessList { // List, da für Arrays keine Exists()-Erweiterung existiert. private List<string> _exculudeList; /// <summary> /// Erstellt eine neue ProcessList-Klasse, /// </summary> /// <param name="exculdeList">Liste von Prozessnamen die nicht aufgelistet werden sollen. </param> /// <param name="listSelf">Wenn True, wird der aufrufende Prozess mit aufgelistet (Standard: False).</param> public ProcessList(string[] exculdeList, bool listSelf = false) { if (exculdeList == null) throw new ArgumentNullException("exculdeList"); this._exculudeList = new List<string>(exculdeList); if (listSelf) this._exculudeList.Add(Process.GetCurrentProcess().ProcessName); } public Dictionary<string, string> GetProcesses() { return Process.GetProcesses() .Where(proc => proc.HasWindow() && this._exculudeList.Exists(excludeName => excludeName != proc.ProcessName)) .ToDictionary( proc => proc.MainWindowTitle, proc => string.Format("{0} (PID: {1})", proc.ProcessName, proc.Id)); } } public static class Extensions { /// <summary> /// Bestimmt ob ein Prozess ein Fenster besitzt. /// </summary> /// <param name="proc">Zu überpfrüfender Prozess</param> /// <returns>True wenn der Prozess ein Fenster besitzt.</returns> public static bool HasWindow(this Process proc) { return proc.MainWindowHandle != IntPtr.Zero; } /// <summary> /// Bestimmt ob zwei Dictionarys die gleichen Schlüssel besitzen. /// </summary> /// <typeparam name="TKey">Der Typ von Element Key</typeparam> /// <typeparam name="TElement">Der Typ von Element Element</typeparam> /// <param name="source">Das Dictionary</param> /// <param name="target">Das zu vergleichende Dictionary</param> /// <returns>True wenn die Dictionarys die gleichen Schlüssel besitzen.</returns> public static bool CompareByKeys<TKey, TElement>(this Dictionary<TKey, TElement> source, Dictionary<TKey, TElement> target) { return source.OrderBy(pair => pair.Key).SequenceEqual(target.OrderBy(pair => pair.Key)); } } }

using System; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Diagnostics; namespace FensterAusgeben { class Program { [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] private static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); static Process p; static void Main(string[] args) { Timer timer = new Timer(); p = Process.GetCurrentProcess(); timer.Interval = 100; timer.Enabled = true; timer.Start(); timer.Tick += new EventHandler(timer_Tick); while (true) { System.Threading.Thread.Sleep(100); Application.DoEvents(); } } private static void timer_Tick(object sender, EventArgs e) { if (p.Id != GetActiveProcess().Id) { p = GetActiveProcess(); if (p.Id != Process.GetCurrentProcess().Id && p.ProcessName != "explorer" && p.ProcessName != "Idle") { Console.WriteLine("Fenstername: " + p.MainWindowTitle); Console.WriteLine("Prozessname: " + p.ProcessName + "\r\n"); } } } private static Process GetActiveProcess() { IntPtr hwnd = GetForegroundWindow(); return hwnd != null ? GetProcessByHandle(hwnd): null; } private static Process GetProcessByHandle(IntPtr hwnd) { try { uint processId; GetWindowThreadProcessId(hwnd, out processId); return Process.GetProcessById((int)processId); } catch { return null; } } } }

using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace Übungen_Zu_CSharp_45 { class Program { //Import der zwei benötigten Funktionen [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll", SetLastError = true)] static extern uint GetWindowThreadProcessId(IntPtr frgWnd, out uint frgWndProcessId); static void Main() { string ProcessTitel = ""; while (true) { //Felder uint ProcessId; string ProcessName; string tempProcessTitel; Process currProc = new Process(); currProc = Process.GetCurrentProcess(); IntPtr fw = GetForegroundWindow(); //Fenster im Vordergrund bestimmen GetWindowThreadProcessId(fw, out ProcessId); //Fensternamen und Prozessnamen auslesen tempProcessTitel = Process.GetProcessById(Convert.ToInt32(ProcessId)).MainWindowTitle; ProcessName = Process.GetProcessById(Convert.ToInt32(ProcessId)).ProcessName; //Wenn die Konsole oder der Explorer im Vordergrund, das Fenster nicht gewechselt wurde oder der Titel leer wird nichts ausgegeben if (ProcessId == currProc.Id || ProcessName == "explorer" || tempProcessTitel == ProcessTitel || tempProcessTitel == "") { continue; } else { ProcessTitel = tempProcessTitel; } //Konsolenausgabe Console.WriteLine("Fenstername: " + ProcessTitel); Console.WriteLine("Prozessname: " + ProcessName + "\n"); //Resourcen sparen System.Threading.Thread.Sleep(1000); } } } }

namespace Exercise_45 { using System; using System.Diagnostics; using System.Runtime.InteropServices; public static class Program { [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll", SetLastError = true)] private static extern uint GetWindowThreadProcessId(IntPtr frgWnd, out uint frgWndProcessId); private static void Main() { var processTitel = ""; while (true) { var currentProcess = Process.GetCurrentProcess(); var fw = GetForegroundWindow(); GetWindowThreadProcessId(fw, out var processId); var actualProcess = Process.GetProcessById(Convert.ToInt32(processId)).MainWindowTitle; var processName = Process.GetProcessById(Convert.ToInt32(processId)).ProcessName; if (processId == currentProcess.Id || processName == "explorer" || actualProcess == processTitel || actualProcess == "") { continue; } processTitel = actualProcess; Console.WriteLine("Fenstername: " + processTitel); Console.WriteLine("Prozessname: " + processName + "\n"); } } } }

using System; using System.Diagnostics; using System.ComponentModel; using System.Windows; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace TrainYourProgrammer45 { class Program { static void Main(string[] args) { int aktivesProgramm = 0; while (true) { foreach (Process prozess in Process.GetProcesses()) { if (GetActiveWindowTitle() == prozess.MainWindowTitle && prozess.Id != aktivesProgramm && prozess.ProcessName != "TrainYourProgrammer45") { Console.WriteLine("Fenstername: " + prozess.MainWindowTitle); Console.WriteLine("Prozessname: " + prozess.ProcessName); Console.WriteLine(); // ID? aktivesProgramm = prozess.Id; } } } } [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")]static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int zaehler); private static string GetActiveWindowTitle() { const int zaehler = 256; StringBuilder Buff = new StringBuilder(zaehler); IntPtr aktivesFenster = GetForegroundWindow(); if (GetWindowText(aktivesFenster, Buff, zaehler) > 0) { return Buff.ToString(); } else { return null; } } } }