1
我的應用程序是一個單一實例應用程序,關閉時最小化到Windows任務欄。然而,我遇到的一個問題是,當我的應用程序執行時(例如:通過桌面上的快捷方式),儘管最小化到任務欄,應用程序不會恢復。相反,應用程序的另一個實例會打開,但在它意識到另一個實例已在運行時會快速關閉。如何在執行時在任務欄中顯示應用程序?
我想知道在執行應用程序時,我如何能有我的應用程序恢復到正常的窗口狀態,當它在任務欄(在後臺運行?)
謝謝。
我的應用程序是一個單一實例應用程序,關閉時最小化到Windows任務欄。然而,我遇到的一個問題是,當我的應用程序執行時(例如:通過桌面上的快捷方式),儘管最小化到任務欄,應用程序不會恢復。相反,應用程序的另一個實例會打開,但在它意識到另一個實例已在運行時會快速關閉。如何在執行時在任務欄中顯示應用程序?
我想知道在執行應用程序時,我如何能有我的應用程序恢復到正常的窗口狀態,當它在任務欄(在後臺運行?)
謝謝。
首先將此輔助類添加到您的項目中。
Friend Class NativeMethods
<DllImport("user32.dll", CharSet:=CharSet.Auto)> _
Friend Shared Function PostMessage(ByVal hwnd As IntPtr, ByVal msg As Integer, ByVal wparam As IntPtr, ByVal lparam As IntPtr) As Boolean
End Function
<DllImport("user32.dll", CharSet:=CharSet.Auto)> _
Friend Shared Function RegisterWindowMessage(ByVal msg As String) As Integer
End Function
Friend Const HWND_BROADCAST As Integer = &HFFFF
Friend Shared ReadOnly WM_RESTORE As Integer = RegisterWindowMessage("WM_RESTORE")
End Class
然後,您需要爲您的應用程序創建一個入口點。 (或修改,如果你已經有一個)
Public Class Program
Private Sub New()
End Sub
<STAThread()> _
Friend Shared Sub Main()
If (mutex.WaitOne(TimeSpan.Zero, True)) Then
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1()) '<- Replace this with an instance of your main form.
Program.mutex.ReleaseMutex()
Else
NativeMethods.PostMessage(New IntPtr(NativeMethods.HWND_BROADCAST), NativeMethods.WM_RESTORE, IntPtr.Zero, IntPtr.Zero)
End If
End Sub
Shared ReadOnly mutex As Mutex = New Mutex(True, "{A1CD1685-EFC9-4D63-BA66-CF2066857FC4}")
End Class
在你的主窗體添加下面的代碼。
Public Class Form1
Inherits Form
Private Sub Restore()
Me.Show()
End Sub
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If (m.Msg = NativeMethods.WM_RESTORE) Then
Me.Restore()
End If
MyBase.WndProc(m)
End Sub
End Class
最後,將應用程序啓動對象更改爲sub main。
How to: Change the Startup Object for an Application (Visual Basic)
參考
http://sanity-free.org/143/csharp_dotnet_single_instance_application.html
當你說 「任務欄」 你實際上意味着 「通知區域」,即 「系統托盤」?任務欄顯示所有正在運行的應用程序的圖標,而試圖顯示「背景」應用程序。當你說它是一個單實例應用程序時,你的意思是你檢查了項目屬性中的單實例框?如果是這樣,那麼您應該處理應用程序的StartupNextInstance事件,以便在用戶嘗試啓動另一個實例時收到通知。然後你可以恢復你的應用程序的主窗體。 – jmcilhinney