C# :: Aufgabe #45 :: Lösung #2

5 Lösungen Lösungen öffentlich
#45

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.

Konsolenausgabe:

Fenstername:  Windows Task-Manager
Prozessname: taskmgr

Fenstername: Neue Aufgabe erstellen - TRAIN your programmer - Google Chrome
Prozessname: chrome

usw.


#2
vote_ok
von wladi-g (1310 Punkte) - 26.06.2014 um 12:03 Uhr
Quellcode ausblenden C#-Code
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;
            }
        }
    }
}

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben