public void Start() { _cancellationTokenSource = new CancellationTokenSource(); CancellationToken token = _cancellationTokenSource.Token; Task listener = Task.Factory.StartNew(() => { while (true) { IntPtr newFocusedWindowHandle = WindowApi.GetForegroundWindow(); string newFocusedWindowTitle = WindowApi.GetWindowTitle(newFocusedWindowHandle); //Only trigger event & update when focused window title is different if (newFocusedWindowTitle != null && newFocusedWindowTitle != FocusedWindowInfo?.Title) { int threadId = WindowApi.GetWindowProcessId(newFocusedWindowHandle, out int processId); WindowInfo newFocusedWindowInfo = new WindowInfo() { Title = newFocusedWindowTitle, Handle = newFocusedWindowHandle, ProcessId = processId, ThreadId = threadId }; FocusedWindowTitleChanged?.Invoke(this, new FocusedWindowTitleChangedEventArgs() { OldFocusedWindow = FocusedWindowInfo, NewFocusedWindow = newFocusedWindowInfo }); FocusedWindowInfo = newFocusedWindowInfo; } Thread.Sleep(PollDelayMilliseconds); if (token.IsCancellationRequested) { break; } } }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }