Single Instance Appplication in .NET CF
(華)
PockePC里的(X)在很多情况下都会给用户一个错觉,那就是以为按此键就会推出程序。但是此(X)跟一般WinForm程序有点不同,不同的就是此(X)是Minimize而不是Close。。。如果所写的程序里没有注意这一点,那就大有可能会导致出现两个同样的程序在同一时间操作。。。而以下就是怎样去防止此情况的一点点心得跟大家分享。
在此就需要用到P/Invoke来access三个API:
- FindWindowW
- ShowWindow
- SetForegroundWindow
Imports System.Runtime.InteropServices
Module Win32Api
#Region " WIN32API CONSTANT PROTOTYPE"
Public Const SW_RESTORE = 9
#End Region
#Region " WIN32API FUNCTION DECLARATION PROTOTYPE "
<DllImport("coredll.dll")> _
Public Function FindWindowW(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
End Function
<DllImport("coredll.dll")> _
Public Function ShowWindow(ByVal hwnd As IntPtr, ByVal nCmdShow As Integer) As Integer
End Function
<DllImport("coredll.dll")> _
Public Function SetForegroundWindow(ByVal hwnd As IntPtr) As Integer
End Function
#End Region
End Module
Module Win32Api
#Region " WIN32API CONSTANT PROTOTYPE"
Public Const SW_RESTORE = 9
#End Region
#Region " WIN32API FUNCTION DECLARATION PROTOTYPE "
<DllImport("coredll.dll")> _
Public Function FindWindowW(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
End Function
<DllImport("coredll.dll")> _
Public Function ShowWindow(ByVal hwnd As IntPtr, ByVal nCmdShow As Integer) As Integer
End Function
<DllImport("coredll.dll")> _
Public Function SetForegroundWindow(ByVal hwnd As IntPtr) As Integer
End Function
#End Region
End Module
然后再多写一个main ()就完成了,
Module AppGlobal
Public Sub main()
Dim hWnd As IntPtr
hWnd = FindWindowW(vbNullString, "Form1")
If hWnd.ToInt64 = 0 Then
Dim frmMainObj As Form1
frmMainObj = New Form1
Application.Run(frmMainObj)
Else
SetForegroundWindow(hWnd)
ShowWindow(hWnd, SW_RESTORE)
Application.Exit()
End If
End Sub
End Module
Public Sub main()
Dim hWnd As IntPtr
hWnd = FindWindowW(vbNullString, "Form1")
If hWnd.ToInt64 = 0 Then
Dim frmMainObj As Form1
frmMainObj = New Form1
Application.Run(frmMainObj)
Else
SetForegroundWindow(hWnd)
ShowWindow(hWnd, SW_RESTORE)
Application.Exit()
End If
End Sub
End Module
如果有更好的方法,例如不用Win32Api;那不妨提供上来跟大家分享。