簡體   English   中英

如何將焦點設置為已處於運行狀態的應用程序?

[英]How can i set the focus to application which is already in running state?

我開發了一個C#Windows應用程序並創建了它的exe。

我想要的是,當我嘗試運行應用程序時,如果它已經處於運行狀態,則激活該應用程序實例,否則啟動新應用程序。

這意味着我不想多次打開同一個應用程序

使用以下代碼將焦點設置為當前應用程序:

        [DllImport("user32.dll")]
        internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        ... 
        Process currentProcess = Process.GetCurrentProcess();
        IntPtr hWnd = currentProcess.MainWindowHandle;
        if (hWnd != IntPtr.Zero)
        {
            SetForegroundWindow(hWnd);
            ShowWindow(hWnd, User32.SW_MAXIMIZE);
        }

您可以從user32.dll PInvoke SetForegroundWindow()和SetFocus()來執行此操作。

[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);

// SetFocus will just focus the keyboard on your application, but not bring your process to front.
// You don't need it here, SetForegroundWindow does the same.
// Just for documentation.
[DllImport("user32.dll")]
static extern IntPtr SetFocus(HandleRef hWnd);

作為參數,您傳遞要引入前端和焦點的過程的窗口句柄。

SetForegroundWindow(myProcess.MainWindowHandle);

SetFocus(new HandleRef(null, myProcess.Handle)); // not needed

另請參閱msdna上SetForegroundWindow Methode的限制

使用Mutex啟動應用程序的單個實例。 此外,您可以使用Process類在其上查找您的應用程序和SetFocus。 這里http://social.msdn.microsoft.com/Forums/da-DK/csharpgeneral/thread/7fd8e358-9709-47f2-9aeb-6c35c7521dc3

使用以下代碼部分進行exe的多個實例檢查,以及它在表單加載時的真實返回。 要在您的應用中運行此功能,請using System.Diagnostics; 命名空間

private bool CheckMultipleInstanceofApp()
        {
            bool check = false;
            Process[] prc = null;
            string ModName, ProcName;
            ModName = Process.GetCurrentProcess().MainModule.ModuleName;
            ProcName = System.IO.Path.GetFileNameWithoutExtension(ModName);
            prc = Process.GetProcessesByName(ProcName);
            if (prc.Length > 1)
            {
                MessageBox.Show("There is an Instance of this Application running");
                check = true;
                System.Environment.Exit(0);
            }
            return check;
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM