Single Instance Appplication in .NET CF

(華)

PockePC里的(X)在很多情况下都会给用户一个错觉,那就是以为按此键就会推出程序。但是此(X)跟一般WinForm程序有点不同,不同的就是此(X)是Minimize而不是Close。。。如果所写的程序里没有注意这一点,那就大有可能会导致出现两个同样的程序在同一时间操作。。。而以下就是怎样去防止此情况的一点点心得跟大家分享。

在此就需要用到P/Invoke来access三个API:
  - FindWindowW
  - ShowWindow
  - SetForegroundWindow

None.gif Imports  System.Runtime.InteropServices
None.gif
ExpandedBlockStart.gifContractedBlock.gif
Module Win32Api Module Win32Api
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
WIN32API CONSTANT PROTOTYPE#Region " WIN32API CONSTANT PROTOTYPE"
InBlock.gif    
Public Const SW_RESTORE = 9
ExpandedSubBlockEnd.gif
#End Region

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
WIN32API FUNCTION DECLARATION PROTOTYPE#Region " WIN32API FUNCTION DECLARATION PROTOTYPE "
InBlock.gif    
<DllImport("coredll.dll")> _
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public Function FindWindowW()Function FindWindowW(ByVal lpClassName As StringByVal lpWindowName As StringAs IntPtr
ExpandedSubBlockEnd.gif    
End Function

InBlock.gif
InBlock.gif    
<DllImport("coredll.dll")> _
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public Function ShowWindow()Function ShowWindow(ByVal hwnd As IntPtr, ByVal nCmdShow As IntegerAs Integer
ExpandedSubBlockEnd.gif    
End Function

InBlock.gif
InBlock.gif    
<DllImport("coredll.dll")> _
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public Function SetForegroundWindow()Function SetForegroundWindow(ByVal hwnd As IntPtr) As Integer
ExpandedSubBlockEnd.gif    
End Function

ExpandedSubBlockEnd.gif
#End Region

InBlock.gif
ExpandedBlockEnd.gif
End Module

然后再多写一个main ()就完成了,

ExpandedBlockStart.gif ContractedBlock.gif Module AppGlobal Module AppGlobal
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public Sub main()Sub main()
InBlock.gif
InBlock.gif        
Dim hWnd As IntPtr
InBlock.gif
InBlock.gif        hWnd 
= FindWindowW(vbNullString, "Form1")
InBlock.gif
InBlock.gif        
If hWnd.ToInt64 = 0 Then
InBlock.gif            
Dim frmMainObj As Form1
InBlock.gif            frmMainObj 
= New Form1
InBlock.gif            Application.Run(frmMainObj)
InBlock.gif        
Else
InBlock.gif            SetForegroundWindow(hWnd)
InBlock.gif            ShowWindow(hWnd, SW_RESTORE)
InBlock.gif            Application.
Exit()
InBlock.gif        
End If
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
ExpandedBlockEnd.gif
End Module

如果有更好的方法,例如不用Win32Api;那不妨提供上来跟大家分享。

转载于:https://www.cnblogs.com/hackzai/archive/2005/06/15/174637.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值