0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

.NET Compact Framework(VB.NET)で二重起動防止(Mutexを利用)する方法

Posted at

Mutexは、ソフトウェアの二重起動の抑止など、さまざまな用途に利用できる排他制御の仕組みです。元々はDigital Equipment Corp.でのVMS開発チームにて開発された、汎用機向けの排他制御の仕組みですが、Windowsには古くから移植されて備わっており、通常のPC向けの.NET Frameworkでは手軽に利用することが出来ます。

しかし、VB.NET CF3.5ではSystem.Threading.Mutexが無いため、Mutex自体をCoredll.dllからP/Invokeする必要があります。

mutextest.vb

Option Strict
Option Explicit
  
Public Class mutextest
 
    <DllImport("CoreDll.Dll", SetLastError:=True)> _
    Public Shared Function CreateMutex(ByVal Attr As IntPtr, ByVal Own As Boolean, ByVal Name As String) As IntPtr
    End Function
 
    <DllImport("CoreDll.Dll", SetLastError:=True)> _
    Public Shared Function ReleaseMutex(ByVal hMutex As IntPtr) As Boolean
    End Function
 
    <DllImport("CoreDll.Dll", SetLastError:=True, CallingConvention:=CallingConvention.Winapi, CharSet:=CharSet.Auto)> _
    Private Shared Function CloseHandle(ByVal hObject As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function
 
    Sub Main()
        '------------------------------------------
        ' 二重起動の確認
        '------------------------------------------
        Const ERROR_ALREADY_EXISTS As Long = 183  '既に起動してるよというエラーコードはこの内容で帰ってくる
 
        Dim mutexHandle As IntPtr = IntPtr.Zero
        Dim myName As String = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
        Try
            mutexHandle = CreateMutex(IntPtr.Zero, True, myName)
            If System.Runtime.InteropServices.Marshal.GetLastWin32Error() = ERROR_ALREADY_EXISTS Then
                'Mutexにより、二重起動時の処理はここに飛んでくる
                Msgbox "二重起動は禁止されています"
 
            Else
                'Mutexにより、二重起動じゃない時の処理はここに飛んでくる
                '-----------------プログラムの開始
  
                'プログラムの本体はここに書いていく
                'お好みでMain()の引数等は処理してください。
 
                '-----------------プログラムの終了
            End If
        Catch ex As Exception
                'mutexのIf文の中で発生した各種エラーに応じた処理はここで行う
                '(デバッグ用のログファイル書き出しとかシステムエラーのダイアログとか)
                Msgbox ex.Message
        End Try
        ReleaseMutex(mutexHandle)
        CloseHandle(mutexHandle)
    End Sub
End Class

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?