アプリケーションの多重起動を禁止する |
Processクラスを使用して、同一モジュールのアプリケーションが起動していれば前面に表示し、多重起動を禁止するサンプルです。アイコン化復帰と前面表示のためにWin32APIを使っています。// クラス hogehoge public class hogehoge { // Win32APIのAPI宣言 [DllImport("user32.dll")] private static extern bool SetForegroundWindow( IntPtr hwnd ); [DllImport("user32.dll")] private static extern bool ShowWindowAsync( IntPtr hwnd, int nCmdShow ); [DllImport("user32.dll")] private static extern bool IsIconic( IntPtr hwnd ); // Win32APIの定数定義 private const int SW_RESTORE = 9; // 静的メソッド public static bool isExistProcess() { // 自分自身のプロセスおよび同じプロセス名のプロセス群を取得 Process curproc = Process.GetCurrentProcess(); Process[] allprocs = Process.GetProcessesByName( curproc.ProcessName ); // 見つかった起動中の同名プロセスを順番に確認する foreach ( Process proc in allprocs ) { // 自分自身のプロセスIDは無視する if ( proc.Id == curproc.Id ) continue; // プロセスのフルパス名を比較して同じアプリケーションか検証する if ( String.Compare( proc.MainModule.FileName, curproc.MainModule.FileName, true ) == 0 ) { // 同一アプリケーションの場合はウインドウハンドルを取得 IntPtr hwnd = proc.MainWindowHandle; // アイコン化されていれば元に戻す if ( IsIconic( hwnd )) ShowWindowAsync( hwnd, SW_RESTORE ); // 前面に表示する SetForegroundWindow( hwnd ); return ( true ); } } // 既に起動している同一アプリケーションは存在しない return ( false ); } }hogehogeクラスを使用して、多重起動を禁止するアプリケーションの記述。 【VB.NETサンプル】 Shared Sub Main() '自身と同一のプログラムプロセスが他にいるかチェックする If (hogehoge.isExistProcess() = True) Then MsgBox("このプログラムはすでに起動しています.", MsgBoxStyle.Exclamation) Exit Sub End If 'フォームをインスタンス化する Application.Run(New Form1) End Sub |