Home‎ > ‎My Notebook‎ > ‎Dev Notes‎ > ‎

C# Notes

Detect Other Applications

using 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.aspx

There 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.Timer

Very 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.Timer

Simply wraps System.Threading.Timer, so still creates a thread in the thread poll.
Adds:
  • A Component implementation, allowing it to be sited in the Visual Studio Designer
  • An Interval property instead of a Change method
  • An Elapsed event instead of a callback delegate
  • An Enabled property to start and pause the timer (its default value being false)
  • Start and Stop methods in case you're confused by Enabled
  • an AutoReset flag for indicating a recurring event (default value true)

3. System.Windows.Forms.Timer

A 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 Calls

System.ComponentModel.BackgroundWorker

  • A cancel flag to tell the thread to terminate with out calling the Abort method.
  • Events for for reporting progress, completion and cancellation.
  • Exception handling on the worker thread.
  • The ability to update Windows Forms and WPF controls in response to worker progress or completion.
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() {
    bw.DoWork += bw_DoWork;
    bw.RunWorkerAsync ("Message to worker");
}
static void bw_DoWork (object sender, DoWorkEventArgs e) {
}

Call Code in the Main Thread

Maybe 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();
            }
        }
Comments