Updating Label with a Task in Winforms [X-Post learningprogramming]

I'm trying to create an application in WinForms that contains a Label (label1). This label should be updated every 500ms with the current process name that has the active focus. For that I'm using GetForegroundWindow() which is working ok there.

I'm trying to run an infinite loop using while (true). My issue started with blocking the UI thread because I was running the loop in the constructor. Googling for a while, I found that I can use a Task for this that will not block the thread, and can update the label running the loop.

My issue is basically that the label isn't getting updated at all. My multithreading/tasks knowledge is almost null, so I'd appreciate if any of you could help me.

Here's the code:

namespace ActiveProc { public partial class Form1 : Form { [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); public Form1() { InitializeComponent(); Task.Factory.StartNew(() => { while (true) { this.label1.Text = GetProcessName(); Thread.Sleep(500); Application.DoEvents(); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } static string GetProcessName() { var ActiveHandler = GetForegroundWindow(); var CurrentProcess = Process.GetProcesses().Where(p => p.MainWindowHandle == ActiveHandler); string ReturnProc = ""; foreach (var Proc in CurrentProcess) { ReturnProc = Proc.ProcessName; } return ReturnProc; } } } 

by aresiusxp via /r/csharp

Leave a Reply