0

WPF で小さなプログラムを作成しました。exe ファイルを実行すると、アプリケーションが正しく開きます。ただし、exeを再度実行すると、もう一度開きます。1回だけ実行したいと思います。

この問題の解決策を検索したところ、次のようなコードが得られました。

System.Diagnostics.Process.GetCurrentProcess().Kill();

このコードは、すべてのアプリケーションを閉じます。ただし、必要なのは、exe を何度も実行するときに、アプリケーションのインスタンスが 1 つだけになることです。

4

2 に答える 2

0

Mutexクラスを使用できます。

  • 特定の名前を持つ Mutex はシステムごとに常に1 つしか存在しない可能性があるため、アプリケーションの最初の起動時にインスタンス化できます。
  • アプリケーションインスタンスがミューテックスを所有できるかどうかは、アプリケーションが開始されるたびに確認できます。
  • そうでない場合は、アプリケーションの別のインスタンスが既に存在することがわかり、新しいインスタンスを適切に閉じることができます。

での作業Mutexは非常に単純明快です。

using System;
using System.Threading;

public class Test
{
    public static void Main()
    {
        // Set this variable to false if you do not want to request  
        // initial ownership of the named mutex. 
        bool requestInitialOwnership = true;
        bool mutexWasCreated;

        // Request initial ownership of the named mutex by passing 
        // true for the first parameter. Only one system object named  
        // "MyMutex" can exist; the local Mutex object represents 
        // this system object. If "MyMutex" is created by this call,
        // then mutexWasCreated contains true; otherwise, it contains 
        // false.
        Mutex m = new Mutex(requestInitialOwnership, 
                            "MyMutex", 
                            out mutexWasCreated);

        // This thread owns the mutex only if it both requested  
        // initial ownership and created the named mutex. Otherwise, 
        // it can request the named mutex by calling WaitOne. 
        if (!(requestInitialOwnership && mutexWasCreated))
        {
           // The mutex is already owned by another application instance.
           // Close gracefully.

           // Put your exit code here...
           // For WPF, this would be Application.Current.Shutdown();
           // (Obviously, that would not work in this Console example.. :-) )
        }

        // Your application code here...
    }
}
于 2012-08-30T07:59:38.220 に答える
0

あなたが正しく理解している場合、同じファイルを再度開くときにアプリケーションを一度だけ開く必要があります。

これを行う方法は、プロセスを強制終了する (ファイルが破損する可能性がある) ことではなく、新しく開いたアプリケーションをすぐに閉じることです。

開いているファイルのリストを中心的な場所 (レジストリ、ファイル) に保持し、アプリケーションの起動時に、ファイルが既にリストにあるかどうかを確認します。新しく起動したアプリケーションを閉じている場合。

要求されたファイルを含むアプリケーションをデスクトップの一番上に表示するコードを追加してみてください。

于 2012-08-30T07:42:54.383 に答える