如何在應(yīng)用程序啟動(dòng)時(shí)執(zhí)行操作
在打開主應(yīng)用程序表單之前,您可能需要在代碼中執(zhí)行某些操作。例如,要啟用DirectX硬件加速,需要?jiǎng)?chuàng)建主應(yīng)用程序表單之前調(diào)用WindowsFormsSettings.ForceDirectXPaint方法。
本主題展示了在 C# 和Visual Basic中開發(fā)項(xiàng)目時(shí)可以將應(yīng)用程序初始化代碼放置在何處,如果您是Visual Basic開發(fā)人員,則可以根據(jù)自己的需求選擇下面列出的方法之一。
C# Example
對(duì)于 C# 項(xiàng)目,在解決方案資源管理器中找到 Program.cs 文件,該文件包含static void Main()過程,您可以在Application.Run方法調(diào)用之前添加自定義代碼。
C# :
using DevExpress.XtraEditors; using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { //Add your code here WindowsFormsSettings.ForceDirectXPaint(); WindowsFormsSettings.EnableFormSkins(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
Visual Basic 示例 - 方法 1
通過這種方法,您可以創(chuàng)建 Main 函數(shù)并將其設(shè)置為應(yīng)用程序的入口點(diǎn)。
1.在解決方案資源管理器中右鍵單擊項(xiàng)目,并在上下文菜單中選擇Properties。
2.取消選中 Enable application framework,然后在Application選項(xiàng)卡中將Startup object設(shè)置為 Sub Main。

3.切換到主表單的代碼編輯器,并手動(dòng)將以下共享主過程添加到表單類中:
VB.NET:
Public Class Form1 Shared Sub Main() Application.EnableVisualStyles() Application.SetCompatibleTextRenderingDefault(False) Application.Run(New Form1) 'Specify the startup form End Sub End Class
4.在應(yīng)用程序之前插入要執(zhí)行的代碼并運(yùn)行方法調(diào)用。
VB.NET:
Public Class Form1 Shared Sub Main() 'Add your code here DevExpress.XtraEditors.WindowsFormsSettings.ForceDirectXPaint() DevExpress.XtraEditors.WindowsFormsSettings.EnableFormSkins() Application.EnableVisualStyles() Application.SetCompatibleTextRenderingDefault(False) Application.Run(New Form1) 'Specify the startup form End Sub End Class
Visual Basic 示例 - 方法 2
通過這種方法,您可以訂閱應(yīng)用程序的啟動(dòng)事件來(lái)執(zhí)行自定義操作。
1.在解決方案資源管理器中右鍵單擊項(xiàng)目,并在上下文菜單中選擇Properties。
2.單擊Application選項(xiàng)卡中的 View Application Events按鈕。

3.在打開的ApplicationEvents.vb文件中訂閱Startup事件。

4.在生成的Startup事件處理程序中插入要執(zhí)行的代碼。
VB.NET:
Imports DevExpress.XtraEditors Imports Microsoft.VisualBasic.ApplicationServices Namespace My ' The following events are available for MyApplication: ' Startup: Raised when the application starts, before the startup form is created. ' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally. ' UnhandledException: Raised if the application encounters an unhandled exception. ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected. Partial Friend Class MyApplication Private Sub MyApplication_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup 'Add your code here WindowsFormsSettings.ForceDirectXPaint() WindowsFormsSettings.EnableFormSkins() End Sub End Class End Namespace