ApplicationContext 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
애플리케이션 스레드에 대한 컨텍스트 정보를 지정합니다.
public ref class ApplicationContext
public ref class ApplicationContext : IDisposable
public class ApplicationContext
public class ApplicationContext : IDisposable
type ApplicationContext = class
type ApplicationContext = class
interface IDisposable
Public Class ApplicationContext
Public Class ApplicationContext
Implements IDisposable
- 상속
-
ApplicationContext
- 구현
예제
다음 코드 예제에서는 두 개의 폼을 표시 하 고 두 형태 모두 닫을 때 애플리케이션을 종료 합니다. 애플리케이션 시작 및 종료, 경우에 각 폼의 위치가 기억 됩니다. 이 예제에 사용 하는 방법을 보여 줍니다.는 ApplicationContext, 함께 Application.Run(context)
애플리케이션을 시작 하는 경우 여러 개의 폼을 표시할 메서드.
클래스 MyApplicationContext
는 에서 ApplicationContext 상속되고 각 양식이 닫힌 시기를 추적하고 둘 다 있을 때 현재 스레드를 종료합니다. 클래스는 사용자에 대한 각 양식의 위치를 저장합니다. 양식 위치 데이터는 에 의해 UserAppDataPath결정된 Appdata.txt
위치에 만들어지는 파일로 저장됩니다.
합니다 Main
메서드 호출 Application.Run(context)
지정 된 애플리케이션을 시작 하는 ApplicationContext합니다.
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
using namespace System::ComponentModel;
using namespace System::Text;
using namespace System::IO;
// A simple form that represents a window in our application
public ref class AppForm2: public System::Windows::Forms::Form
{
public:
AppForm2()
{
this->Size = System::Drawing::Size( 300, 300 );
this->Text = "AppForm2";
}
};
// A simple form that represents a window in our application
public ref class AppForm1: public System::Windows::Forms::Form
{
public:
AppForm1()
{
this->Size = System::Drawing::Size( 300, 300 );
this->Text = "AppForm1";
}
};
// The class that handles the creation of the application windows
ref class MyApplicationContext: public ApplicationContext
{
private:
int _formCount;
AppForm1^ _form1;
AppForm2^ _form2;
System::Drawing::Rectangle _form1Position;
System::Drawing::Rectangle _form2Position;
FileStream^ _userData;
public:
MyApplicationContext()
{
_formCount = 0;
// Handle the ApplicationExit event to know when the application is exiting.
Application::ApplicationExit += gcnew EventHandler( this, &MyApplicationContext::OnApplicationExit );
try
{
// Create a file that the application will store user specific data in.
_userData = gcnew FileStream( String::Concat( 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: {0}", dynamic_cast<String^>(e) );
// 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 = gcnew AppForm1;
_form1->Closed += gcnew EventHandler( this, &MyApplicationContext::OnFormClosed );
_form1->Closing += gcnew CancelEventHandler( this, &MyApplicationContext::OnFormClosing );
_formCount++;
_form2 = gcnew AppForm2;
_form2->Closed += gcnew EventHandler( this, &MyApplicationContext::OnFormClosed );
_form2->Closing += gcnew CancelEventHandler( this, &MyApplicationContext::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();
}
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 ( Exception^ )
{
}
}
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 ( dynamic_cast<AppForm1^>(sender) != nullptr )
_form1Position = (dynamic_cast<Form^>(sender))->Bounds;
else
if ( dynamic_cast<AppForm1^>(sender) != nullptr )
_form2Position = (dynamic_cast<Form^>(sender))->Bounds;
}
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();
}
}
bool WriteFormDataToFile()
{
// Write the form positions to the file.
UTF8Encoding^ encoding = gcnew UTF8Encoding;
RectangleConverter^ rectConv = gcnew RectangleConverter;
String^ form1pos = rectConv->ConvertToString( _form1Position );
String^ form2pos = rectConv->ConvertToString( _form2Position );
array<Byte>^dataToWrite = encoding->GetBytes( String::Concat( "~", 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 ( Exception^ )
{
// An error occurred while attempting to write, return false.
return false;
}
}
bool ReadFormDataFromFile()
{
// Read the form positions from the file.
UTF8Encoding^ encoding = gcnew UTF8Encoding;
String^ data;
if ( _userData->Length != 0 )
{
array<Byte>^dataToRead = gcnew array<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 = dynamic_cast<String^>(e);
// 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 = gcnew RectangleConverter;
String^ form1pos = data->Substring( 1, data->IndexOf( "~", 1 ) - 1 );
_form1Position = *safe_cast<Rectangle^>(rectConv->ConvertFromString( form1pos ));
String^ form2pos = data->Substring( data->IndexOf( "~", 1 ) + 1 );
_form2Position = *safe_cast<Rectangle^>(rectConv->ConvertFromString( form2pos ));
return true;
}
catch ( Exception^ )
{
// 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]
int main()
{
// Create the MyApplicationContext, that derives from ApplicationContext,
// that manages when the application should exit.
MyApplicationContext^ context = gcnew MyApplicationContext;
// Run the application with the specific context. It will exit when
// all forms are closed.
Application::Run( context );
}
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);
}
}
}
Imports System.Drawing
Imports System.Windows.Forms
Imports System.ComponentModel
Imports System.Text
Imports System.IO
' A simple form that represents a window in our application
Public Class AppForm1
Inherits System.Windows.Forms.Form
Public Sub New()
MyBase.New()
Me.Size = New System.Drawing.Size(300, 300)
Me.Text = "AppForm1"
End Sub
End Class
' A simple form that represents a window in our application
Public Class AppForm2
Inherits System.Windows.Forms.Form
Public Sub New()
MyBase.New()
Me.Size = New System.Drawing.Size(300, 300)
Me.Text = "AppForm2"
End Sub
End Class
' The class that handles the creation of the application windows
Public Class MyApplicationContext
Inherits ApplicationContext
Private _formCount As Integer
Private _form1 As AppForm1
Private _form2 As AppForm2
Private _form1Position As Rectangle
Private _form2Position As Rectangle
Private _userData As FileStream
Public Sub New()
MyBase.New()
_formCount = 0
' Handle the ApplicationExit event to know when the application is exiting.
AddHandler Application.ApplicationExit, AddressOf OnApplicationExit
Try
' Create a file that the application will store user specific data in.
_userData = New FileStream(Application.UserAppDataPath + "\appdata.txt", FileMode.OpenOrCreate)
Catch e As IOException
' 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()
End Try
' Create both application forms and handle the Closed event
' to know when both forms are closed.
_form1 = New AppForm1()
AddHandler _form1.Closed, AddressOf OnFormClosed
AddHandler _form1.Closing, AddressOf OnFormClosing
_formCount = _formCount + 1
_form2 = New AppForm2()
AddHandler _form2.Closed, AddressOf OnFormClosed
AddHandler _form2.Closing, AddressOf OnFormClosing
_formCount = _formCount + 1
' Get the form positions based upon the user specific data.
If (ReadFormDataFromFile()) Then
' 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
End If
' Show both forms.
_form1.Show()
_form2.Show()
End Sub
Private Sub OnApplicationExit(ByVal sender As Object, ByVal e As EventArgs)
' 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
End Try
End Sub
Private Sub OnFormClosing(ByVal sender As Object, ByVal e As CancelEventArgs)
' When a form is closing, remember the form position so it
' can be saved in the user data file.
If TypeOf sender Is AppForm1 Then
_form1Position = CType(sender, Form).Bounds
ElseIf TypeOf sender Is AppForm2 Then
_form2Position = CType(sender, Form).Bounds
End If
End Sub
Private Sub OnFormClosed(ByVal sender As Object, ByVal e As EventArgs)
' When a form is closed, decrement the count of open forms.
' When the count gets to 0, exit the app by calling
' ExitThread().
_formCount = _formCount - 1
If (_formCount = 0) Then
ExitThread()
End If
End Sub
Private Function WriteFormDataToFile() As Boolean
' Write the form positions to the file.
Dim encoding As UTF8Encoding = New UTF8Encoding()
Dim rectConv As RectangleConverter = New RectangleConverter()
Dim form1pos As String = rectConv.ConvertToString(_form1Position)
Dim form2pos As String = rectConv.ConvertToString(_form2Position)
Dim dataToWrite As Byte() = 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
End Try
End Function
Private Function ReadFormDataFromFile() As Boolean
' Read the form positions from the file.
Dim encoding As UTF8Encoding = New UTF8Encoding()
Dim data As String
If (_userData.Length <> 0) Then
Dim dataToRead(_userData.Length) As Byte
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 e As IOException
Dim errorInfo As String = e.ToString()
' An error occurred while attempt to read, return false.
Return False
End Try
' Parse out the data to get the window rectangles
data = encoding.GetString(dataToRead)
Try
' Convert the string data to rectangles
Dim rectConv As RectangleConverter = New RectangleConverter()
Dim form1pos As String = data.Substring(1, data.IndexOf("~", 1) - 1)
_form1Position = CType(rectConv.ConvertFromString(form1pos), Rectangle)
Dim form2pos As String = data.Substring(data.IndexOf("~", 1) + 1)
_form2Position = CType(rectConv.ConvertFromString(form2pos), Rectangle)
Return True
Catch
' Error occurred while attempting to convert the rectangle data.
' Return false to use default values.
Return False
End Try
Else
' No data in the file, return false to use default values.
Return False
End If
End Function
End Class
Public Module MyApplication
Public Sub Main()
' Create the MyApplicationContext, that derives from ApplicationContext,
' that manages when the application should exit.
Dim context As MyApplicationContext = New MyApplicationContext()
' Run the application with the specific context. It will exit when
' all forms are closed.
Application.Run(context)
End Sub
End Module
설명
클래스를 ApplicationContext 사용하여 메시지 루프가 종료되는 상황을 재정의할 수 있습니다. 기본적으로 ApplicationContext 를 수신 하는 Closed 애플리케이션에서 이벤트의 주 Form, 다음 스레드의 메시지 루프를 종료 합니다.
생성자
ApplicationContext() |
컨텍스트를 사용하지 않고 ApplicationContext 클래스의 새 인스턴스를 초기화합니다. |
ApplicationContext(Form) |
지정된 ApplicationContext를 사용하여 Form 클래스의 새 인스턴스를 초기화합니다. |
속성
MainForm |
컨텍스트로 사용할 Form을 가져오거나 설정합니다. |
Tag |
컨트롤에 대한 데이터가 들어 있는 개체를 가져오거나 설정합니다. |
메서드
Dispose() |
ApplicationContext에서 사용하는 모든 리소스를 해제합니다. |
Dispose(Boolean) |
ApplicationContext에서 사용하는 관리되지 않는 리소스를 해제하고, 관리되는 리소스를 선택적으로 해제할 수 있습니다. |
Equals(Object) |
지정된 개체가 현재 개체와 같은지 확인합니다. (다음에서 상속됨 Object) |
ExitThread() |
스레드의 메시지 루프를 종료합니다. |
ExitThreadCore() |
스레드의 메시지 루프를 종료합니다. |
Finalize() |
가비지 수집에 의해 애플리케이션 컨텍스트가 회수되기 전에 리소스를 해제하고 다른 정리 작업을 수행하려고 합니다. |
GetHashCode() |
기본 해시 함수로 작동합니다. (다음에서 상속됨 Object) |
GetType() |
현재 인스턴스의 Type을 가져옵니다. (다음에서 상속됨 Object) |
MemberwiseClone() |
현재 Object의 단순 복사본을 만듭니다. (다음에서 상속됨 Object) |
OnMainFormClosed(Object, EventArgs) |
ExitThreadCore() 이벤트를 발생시키는 ThreadExit를 호출합니다. |
ToString() |
현재 개체를 나타내는 문자열을 반환합니다. (다음에서 상속됨 Object) |
이벤트
ThreadExit |
ExitThread()를 호출하여 스레드의 메시지 루프를 종료할 때 발생합니다. |
적용 대상
.NET