Sunday, 16 February 2020

C# - EventHandler Delegate (Generic EventHandler Delegate)

Represents the method that will handle an event when the event provides data.


using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Counter c = new Counter(new Random().Next(10));
            c.ThresholdReached += c_ThresholdReached;

            Console.WriteLine("press 'a' key to increase total");
            while (Console.ReadKey(true).KeyChar == 'a')
            {
                Console.WriteLine("adding one");
                c.Add(1);
            }
        }

        static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e)
        {
            Console.WriteLine("The threshold of {0} was reached at {1}.",
                              e.Threshold, 
                              e.TimeReached);
            Environment.Exit(0);
        }
    }

    class Counter
    {
        private int threshold;
        private int total;

        public Counter(int passedThreshold)
        {
            threshold = passedThreshold;
        }

        public void Add(int x)
        {
            total += x;
            if (total >= threshold)
            {
                ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
                args.Threshold = threshold;
                args.TimeReached = DateTime.Now;
                OnThresholdReached(args);
            }
        }

        protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
        {
            EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;
    }

    public class ThresholdReachedEventArgs : EventArgs
    {
        public int Threshold { get; set; }
        public DateTime TimeReached { get; set; }
    }
}

Thursday, 6 February 2020

C# - Windows Forms Event Sequence


The order in which events are raised in Windows Forms applications is of particular interest to developers concerned with handling each of these events in turn. When a situation calls for meticulous handling of events, such as when you are redrawing parts of the form, an awareness of the precise order in which events are raised at run time is necessary. This topic provides some details on the order of events during several important stages in the lifetime of applications and controls.

Application Startup and Shutdown Events

The Form and Control classes expose a set of events related to application startup and shutdown. When a Windows Forms application starts, the startup events of the main form are raised in the following order:
·         Control.HandleCreated
·         Control.BindingContextChanged
·         Form.Load
·         Control.VisibleChanged
·         Form.Activated
·         Form.Shown

When an application closes, the shutdown events of the main form are raised in the following order:
·         Form.Closing
·         Form.FormClosing
·         Form.Closed
·         Form.FormClosed
·         Form.Deactivate

Windows Forms Event Sequence
Form Start up
Event
Description
1.
Control.HandleCreated
Occurs when a handle is created for the control.
2.
Control.BindingContextChanged
Occurs when the value of the BindingContext property changes.
3.
Form.Load
Occurs before a form is displayed for the first time.
4.
Control.VisibleChanged
Occurs when the Visible property value changes.
5.
Form.Activated
Occurs when the form is activated in code or by the user.
6.
Form.Shown
Occurs whenever the form is first displayed.

Form Shutdown
Event
Description
1.
Form.Closing
Occurs when the form is closing.
2.
Form.FormClosing
Occurs before the form is closed.
3.
Form.Closed
Occurs when the form is closed.
4.
Form.FormClosed
Occurs after the form is closed.
5.
Form.Deactivate
Occurs when the form loses focus and is no longer the active form.


Wednesday, 5 February 2020

C# - Form.Close() Vs Application.Exit() Vs Environment.Exit()

Form.Close Method
When a form is closed, all resources created within the object are closed and the form is disposed. You can prevent the closing of a form at run time by handling the Closing event and setting the Cancel property of the CancelEventArgs passed as a parameter to your event handler. If the form you are closing is the startup form of your application, your application ends.
The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection.
--Note
When the Close method is called on a Form displayed as a modeless window, you cannot call the Show method to make the form visible, because the form's resources have already been released. To hide a form and then make it visible, use the Control.Hide method.
--Caution
Prior to the .NET Framework 2.0, the Form.Closed and Form.Closing events are not raised when the Application.Exit method is called to exit your application. If you have validation code in either of these events that must be executed, you should call the Form.Close method for each open form individually before calling the Exit method.

Application.Exit Method
Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.
Overloads
Exit()
Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.
Exit(CancelEventArgs)
Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.

Environment.Exit(Int32) Method
Terminates this process and returns an exit code to the operating system.
Remarks
For the exitCode parameter, use a non-zero number to indicate an error. In your application, you can define your own error codes in an enumeration, and return the appropriate error code based on the scenario. For example, return a value of 1 to indicate that the required file is not present, and a value of 2 to indicate that the file is in the wrong format. For a list of exit codes used by the Windows operating system, see System Error Codes in the Windows documentation.
Calling the Exit method differs from using your programming language's return statement in the following ways:
Exit always terminates an application. Using the return statement may terminate an application only if it is used in the application entry point, such as in the Main method.
Exit terminates an application immediately, even if other threads are running. If the return statement is called in the application entry point, it causes an application to terminate only after all foreground threads have terminated.
Exit requires the caller to have permission to call unmanaged code. The return statement does not.
If Exit is called from a try or catch block, the code in any finally block does not execute. If the return statement is used, the code in the finally block does execute.
If Exit is called when code in a constrained execution region (CER) is running, the CER will not complete execution. If the return statement is used, the CER completes execution.

Sunday, 2 February 2020

C# - FolderBrowserDialog


// Open rich text files (rtf) into the RichTextBox using the FolderBrowserDialog
// to set the default directory for opening files.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

public class FolderBrowserDialogExampleForm : System.Windows.Forms.Form
{
    private FolderBrowserDialog folderBrowserDialog1;
    private OpenFileDialog openFileDialog1;

    private RichTextBox richTextBox1;

    private MainMenu mainMenu1;
    private MenuItem fileMenuItem, openMenuItem;
    private MenuItem folderMenuItem;

    private string openFileName, folderName;

    private bool fileOpened = false;

    // The main entry point for the application.
    [STAThreadAttribute]
    static void Main()
    {
        Application.Run(new FolderBrowserDialogExampleForm());
    }

    // Constructor.
    public FolderBrowserDialogExampleForm()
    {
        this.mainMenu1 = new System.Windows.Forms.MainMenu();
        this.fileMenuItem = new System.Windows.Forms.MenuItem();
        this.openMenuItem = new System.Windows.Forms.MenuItem();
        this.folderMenuItem = new System.Windows.Forms.MenuItem();
       
        this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
        this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
        this.richTextBox1 = new System.Windows.Forms.RichTextBox();

        this.mainMenu1.MenuItems.Add(this.fileMenuItem);
        this.fileMenuItem.MenuItems.AddRange(
                            new System.Windows.Forms.MenuItem[]  {this.openMenuItem,
                                                                 this.folderMenuItem});
        this.fileMenuItem.Text = "File";

        //(1)
        this.openMenuItem.Text = "Open...";
        this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click);

        //(2)
        this.folderMenuItem.Text = "Select Directory...";
        this.folderMenuItem.Click += new System.EventHandler(this.folderMenuItem_Click);

        this.openFileDialog1.DefaultExt = "TXT";
        this.openFileDialog1.Filter = "TXT files (*.txt)|*.txt";

        this.folderBrowserDialog1.Description =
                            "Select the directory that you want to use as the default.";
        this.folderBrowserDialog1.ShowNewFolderButton = false;
        this.folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;

        this.richTextBox1.AcceptsTab = true;
        this.richTextBox1.Location = new System.Drawing.Point(8, 8);
        this.richTextBox1.Size = new System.Drawing.Size(280, 344);
        this.richTextBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left |
                                   AnchorStyles.Bottom | AnchorStyles.Right;

        this.ClientSize = new System.Drawing.Size(296, 360);
        this.Controls.Add(this.richTextBox1);
        this.Menu = this.mainMenu1;
        this.Text = "TXT Document Browser";
    }
       
    private void openMenuItem_Click(object sender, System.EventArgs e)
    {      
        if (!fileOpened)
        {
            openFileDialog1.InitialDirectory = folderBrowserDialog1.SelectedPath;
            openFileDialog1.FileName = null;
        }
      
        DialogResult result = openFileDialog1.ShowDialog();
      
        if (result == DialogResult.OK)
        {
            openFileName = openFileDialog1.FileName;
            try
            {
                // Output the requested file in richTextBox1.
                Stream s = openFileDialog1.OpenFile();
                richTextBox1.LoadFile(s, RichTextBoxStreamType.PlainText);
                //richTextBox1.LoadFile(
                //openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
                s.Close();

                fileOpened = true;
            }
            catch (Exception exp)
            {
                MessageBox.Show(
                       "An error occurred while attempting to load the file. The error is:"
                                + System.Environment.NewLine + exp.ToString()
                                + System.Environment.NewLine);
                fileOpened = false;
            }
            Invalidate();           
        }       
        else if (result == DialogResult.Cancel)
        {
            return;
        }
    }  

    private void folderMenuItem_Click(object sender, System.EventArgs e)
    {       
        DialogResult result = folderBrowserDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            folderName = folderBrowserDialog1.SelectedPath;
            if (!fileOpened)
            {              
                openFileDialog1.InitialDirectory = folderName;
                openFileDialog1.FileName = null;
                openMenuItem.PerformClick();
            }
        }
    }
}