Solved

What is the use of ApplicationContext Class in C#.net window application ??

Posted on 2011-03-09
4
2,171 Views
Last Modified: 2012-05-11
What is the use of ApplicationContext Class in C#.net window application ??

can u please tell me step by step so that i can understand ?

can i use it in form (code behind) or i have to use it only in program.cs file ??
0
Comment
Question by:Parth48
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 10

Expert Comment

by:Asim Nazir
ID: 35082356
Application context specifies the contextual information about an application thread.
Details at http://msdn.microsoft.com/en-us/library/system.windows.forms.applicationcontext.aspx
0
 

Author Comment

by:Parth48
ID: 35091408
hi @asimnazir123: yes u r right , but what is the meaning of contextual information ??

can u please tell me some practical exam where we can use application context class ??
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 35091727
Put simply, implementing your own ApplicationContext() allows YOU to decide how and when your application closes.

The default WinForms model is tied to the lifetime of the Form passed to Application.Run().  When that form is closed the entire application shuts down.

An ApplicationContext() gives you the ability to keep your application open under whatever circumstances you want.  The entry point becomes the constructor of the class from which you could display a form if you wanted to.   Even if that form is closed your app will continue running because the class still exists and has its own message pump.  When the conditions are right for your particular program, you tell the app to shutdown by calling Application.Exit().
0
 
LVL 10

Accepted Solution

by:
Asim Nazir earned 500 total points
ID: 35091816
Ok. Here is the meaning of Contextual information:

“Context is any information that can be used to characterize the situation of an entity. An entity is a person, place, or object that is considered relevant to the interaction between a user and an application, including the user and application themselves.”

Furthermore, contextual information can be any kind of information that characterises or provides additional information regarding any feature or condition of the delivery and consumption environment. Entities, either software or hardware, that are able to generate and provide this explicit contextual information are designated as Context Providers (CxPs).

Here is practical example with detail:

You can use the ApplicationContext class to redefine the circumstances that cause a message loop to exit. By default, the ApplicationContext listens to the Closed event on the application's main Form, then exits the thread's message loop.

Examples
--------------------------------------------------------------------------------

The following code example displays two forms and exits the application when both forms are closed. When the application starts and exits, the position of each form is remembered. This example demonstrates how to use an ApplicationContext, along with the Application.Run(context) method, to display multiple forms when the application starts.

The class MyApplicationContext inherits from ApplicationContext and keeps track when each form is closed, and exits the current thread when they both are. The class stores the positions of each form for the user. The form position data is stored in a file titled Appdata.txt that is created in the location determined by UserAppDataPath.

The Main method calls Application.Run(context) to start the application, given the ApplicationContext.

 
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Text;
using System.IO;

namespace MyApplication
{
    // A simple form that represents a window in our application
    public class AppForm2 : System.Windows.Forms.Form {
        public AppForm2(){ 
            this.Size = new System.Drawing.Size(300,300);
            this.Text = "AppForm2";
        }
    }

    // A simple form that represents a window in our application
    public class AppForm1 : System.Windows.Forms.Form {
        public AppForm1(){ 
            this.Size = new System.Drawing.Size(300,300);
            this.Text = "AppForm1";
        }
    }

    // The class that handles the creation of the application windows
    class MyApplicationContext : ApplicationContext {

        private int formCount;
        private AppForm1 form1;
        private AppForm2 form2;

        private Rectangle form1Position;
        private Rectangle form2Position;

        private FileStream userData;

        private MyApplicationContext() {
            formCount = 0;

            // Handle the ApplicationExit event to know when the application is exiting.
            Application.ApplicationExit += new EventHandler(this.OnApplicationExit);

            try {
                // Create a file that the application will store user specific data in.
                userData = new FileStream(Application.UserAppDataPath + "\\appdata.txt", FileMode.OpenOrCreate);

            } catch(IOException e) {
                // Inform the user that an error occurred.
                MessageBox.Show("An error occurred while attempting to show the application." + 
                                "The error is:" + e.ToString());

                // Exit the current thread instead of showing the windows.
                ExitThread();
            }

            // Create both application forms and handle the Closed event
            // to know when both forms are closed.
            form1 = new AppForm1();
            form1.Closed += new EventHandler(OnFormClosed);            
            form1.Closing += new CancelEventHandler(OnFormClosing);            
            formCount++;

            form2 = new AppForm2();
            form2.Closed += new EventHandler(OnFormClosed);            
            form2.Closing += new CancelEventHandler(OnFormClosing);            
            formCount++;

            // Get the form positions based upon the user specific data.
            if (ReadFormDataFromFile()) {
                // If the data was read from the file, set the form
                // positions manually.
                form1.StartPosition = FormStartPosition.Manual;
                form2.StartPosition = FormStartPosition.Manual;

                form1.Bounds = form1Position;
                form2.Bounds = form2Position;
            }

            // Show both forms.
            form1.Show();
            form2.Show();
        }

        private void OnApplicationExit(object sender, EventArgs e) {
            // When the application is exiting, write the application data to the
            // user file and close it.
            WriteFormDataToFile();

            try {
                // Ignore any errors that might occur while closing the file handle.
                userData.Close();
            } catch {}
        }

        private void OnFormClosing(object sender, CancelEventArgs e) {
            // When a form is closing, remember the form position so it
            // can be saved in the user data file.
            if (sender is AppForm1) 
                form1Position = ((Form)sender).Bounds;
            else if (sender is AppForm2)
                form2Position = ((Form)sender).Bounds;
        }

        private void OnFormClosed(object sender, EventArgs e) {
            // When a form is closed, decrement the count of open forms.

            // When the count gets to 0, exit the app by calling
            // ExitThread().
            formCount--;
            if (formCount == 0) {
                ExitThread();
            }
        }

        private bool WriteFormDataToFile(){
            // Write the form positions to the file.
            UTF8Encoding encoding = new UTF8Encoding();

            RectangleConverter rectConv = new RectangleConverter();
            String form1pos = rectConv.ConvertToString(form1Position);
            String form2pos = rectConv.ConvertToString(form2Position);

            byte[] dataToWrite = encoding.GetBytes("~" + form1pos + "~" + form2pos);

            try {
                // Set the write position to the start of the file and write
                userData.Seek(0,SeekOrigin.Begin);
                userData.Write(dataToWrite, 0, dataToWrite.Length);
                userData.Flush();

                userData.SetLength(dataToWrite.Length);
                return true;

            } catch {
                // An error occurred while attempting to write, return false.
                return false;
            }

        }

        private bool ReadFormDataFromFile(){
            // Read the form positions from the file.
            UTF8Encoding encoding = new UTF8Encoding();
            String data;

            if (userData.Length != 0) {
                byte[] dataToRead = new Byte[userData.Length];

                try {
                    // Set the read position to the start of the file and read.
                    userData.Seek(0, SeekOrigin.Begin);
                    userData.Read(dataToRead, 0, dataToRead.Length);

                } catch (IOException e) {
                    String errorInfo = e.ToString();
                    // An error occurred while attempt to read, return false.
                    return false;
                }

                // Parse out the data to get the window rectangles
                data = encoding.GetString(dataToRead);

                try {
                    // Convert the string data to rectangles
                    RectangleConverter rectConv = new RectangleConverter();
                    String form1pos = data.Substring(1,data.IndexOf("~",1)-1);

                    form1Position = (Rectangle)rectConv.ConvertFromString(form1pos);

                    String form2pos = data.Substring(data.IndexOf("~",1)+1);
                    form2Position = (Rectangle)rectConv.ConvertFromString(form2pos);

                    return true;

                } catch {
                    // Error occurred while attempting to convert the rectangle data.
                    // Return false to use default values.
                    return false;
                }

            } else {
                // No data in the file, return false to use default values.
                return false;
            }
        }        

        [STAThread]
        static void Main(string[] args) {

            // Create the MyApplicationContext, that derives from ApplicationContext,
            // that manages when the application should exit.

            MyApplicationContext context = new MyApplicationContext();

            // Run the application with the specific context. It will exit when
            // all forms are closed.
            Application.Run(context);

        }
    }
}

Open in new window


I hope it helps.

Asim
0

Featured Post

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

732 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question