Detect Other Applicationsusing System.Diagnostics; Process[] processes = Process.GetProcessesByName("notepad"); foreach (Process p in processes) { IntPtr pFoundWindow = p.MainWindowHandle; // Do something with the handle... // Or Close the window p.CloseMainWindow(); } Timers in C#http://www.albahari.com/threading/part3.aspxThere are three types of Timers available in C#. The first 2 use the Thread Pool, which recycles threads to avoid recreating them for each new task. No need to call Abort. 1. System.Threading.TimerVery simple, basic thread. timer = new Timer(new TimerCallback(callback), null, msecDelay, Timeout.Infinite); //infinite means no repeated calls - effectively a oneshot timer timer = new Timer(new TimerCallback(callback), null, 0, 1000); // 0 = start immediately and repeat every 1000 ms timer = new Timer(new TimerCallback(callback), null, Timeout.Infinite, 1000); // Timeout.Infinite means suspend the thread for now Call timer.Change() to reset these settings at any time. 2. System.Timers.TimerSimply wraps System.Threading.Timer, so still creates a thread in the thread poll. Adds:
3. System.Windows.Forms.TimerA different beast. Thread pool is not used. Tick event is synchronized for you - on the same
thread that originally created the timer. So when created on the main thread it's safe to interact with form controls. And being on the main thread make sure you so stuff very quickly so you don't hold up any other UI stuff. Other Thread CallsSystem.ComponentModel.BackgroundWorker
No need to include a try/catch block in your worker
method You can update Windows Forms and WPF controls without needing to call Control.Invoke. Uses the thread-pool, so one should never call Abort on a BackgroundWorker thread. static BackgroundWorker bw = new BackgroundWorker(); static void Main() { static void bw_DoWork (object sender, DoWorkEventArgs e) { Call Code in the Main ThreadMaybe we don't know if we are in the main thread or another thread. We can improve our code as follows...In this example I want to check a button. Normally we'd simply call -- this.buttonRss.Checked = true; In this thread code we call RssChecked(true); instead. delegate void SetCheckCallback(Boolean checkState); private void RssChecked(Boolean checkState) { if (InvokeRequired) { SetCheckCallback d = new SetCheckCallback(RssChecked); this.Invoke(d, new object[] { checkState }); } else { this.buttonRss.Checked = checkState; this.buttonRss.Refresh(); } } |