如何启用一个应用程序的多个实例?
-
发布时间:2010-11-23 16:19:45
发布时间:2010-11-23 16:19:45
.NET Compact Framework 不支持多实例。以下代码示例提供了一种解决方案,它允许当启动应用程序时(但是已有一个运行着的实例)实例化而非最大化应用程序。
注:并非所有版本的 OS(包括未来版本)都支持以下代码,也不保证在所有这些版本中都能工作。
// C#
using System.Runtime.InteropServices; using System.Reflection; private void Form1_Load(object sender, System.EventArgs e) { this.Text = string.Format("Form {0}", new Random().Next()); } [DllImport("CoreDll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("CoreDll")] public static extern int SetWindowText(IntPtr hWnd, string lpString); protected override void OnResize(EventArgs e) { Assembly asm = System.Reflection.Assembly.GetExecutingAssembly(); IntPtr hWnd = FindWindow("#NETCF_AGL_PARK_", asm.GetModules()[0].FullyQualifiedName); if (hWnd != IntPtr.Zero) SetWindowText(hWnd, "#42"); base.OnResize (e); } 'VB Imports System.Runtime.InteropServices Imports System.Reflection Private Sub Form1_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Me.Text = String.Format("Form {0}", New Random().Next()) End Sub 'Form1_Load _ Public Shared Function FindWindow(ByVal lpClassName As String, _ ByVal lpWindowName As String) As IntPtr End Function _ Public Shared Function SetWindowText(ByVal hWnd As IntPtr, _ ByVal lpString As String) As Integer End Function Protected Overrides Sub OnResize(ByVal e As EventArgs) Dim asm As [Assembly] = System.Reflection.Assembly.GetExecutingAssembly() Dim hWnd As IntPtr = FindWindow("#NETCF_AGL_PARK_", _ asm.GetModules()(0).FullyQualifiedName) If hWnd.ToInt32() <> IntPtr.Zero.ToInt32() Then SetWindowText(hWnd, "#42") End If MyBase.OnResize(e) End Sub 'OnResize