如何使vb Form使用Mutex成为单个实例。对于开发人员!
嗨, 我在网上搜索了如何在VB Net中而不是在C#代码中创建单实例启动表单。这是我的解决方案:
添加此引用:Imports System.Runtime.InteropServices
Public Const HWND_BROADCAST As Integer = &HFFFF
Public Shared ReadOnly WM_SHOWME As Integer = RegisterWindowMessage("WM_SHOWME")
<DllImport("user32")>
Public 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")>
Public Shared Function RegisterWindowMessage(ByVal message As String) As Integer
End Function
添加此引用:Imports System.Threading
Public Sub Main()
Dim Mutex As Mutex = New Mutex(True, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}")
If Mutex.WaitOne(TimeSpan.Zero, True) Then
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1())
Mutex.ReleaseMutex()
Else
MessageBox.Show("Another instance of this Application is already running.", "Attention Requested", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
NativeMethods.PostMessage(CType(NativeMethods.HWND_BROADCAST, IntPtr), NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero)
End If
End Sub
Private Const SW_HIDE As Integer = 0
Private Const SW_SHOWNORMAL As Integer = 1
Private Const SW_SHOWMINIMIZED As Integer = 2
Private Const SW_SHOWMAXIMIZED As Integer = 3
Private Const SW_SHOWNOACTIVATE As Integer = 4
Private Const SW_RESTORE As Integer = 9
Private Const SW_SHOWDEFAULT As Integer = 10
Protected Overrides Sub WndProc(ByRef m As Message)
Const WM_SYSCOMMAND As Integer = &H112
Const SC_RESTORE As Integer = &HF120
Const SC_MINIMIZE As Integer = &HF020
If m.Msg = NativeMethods.WM_SHOWME Then
ShowMe()
End If
If m.Msg = WM_SYSCOMMAND AndAlso CInt(m.WParam) = SC_RESTORE Then
End If
If m.Msg = WM_SYSCOMMAND AndAlso CInt(m.WParam) = SC_MINIMIZE Then
End If
MyBase.WndProc(m)
End Sub
Private Sub ShowMe()
If WindowState = FormWindowState.Minimized Then
WindowState = FormWindowState.Normal
End If
Show()
Dim top As Boolean = TopMost
TopMost = True
TopMost = top
'Here you can call your own function. For example if your application uses the command line!
End Sub
此解决方案效果很好,并且已经在Windows 7 / 8.1和10 32/64位上进行了测试。如果有人找到更好的解决方案,请发布它。 谢谢和最好的问候。