3

我有一个 Dictionary WPF 应用程序,我用热键 (Alt + A) 将它链接起来,这个应用程序在其 window_activated 事件中检查剪贴板中复制的文本并立即翻译它。

现在,当用户点击热键(Alt + A)时,会创建一个新的应用程序实例,所以我决定将其限制为一个实例,我设法做到了,但问题就在这里

用户点击(Alt + A)新实例被中止但先前存在的实例正在运行但我无法激活要激活的窗口这里是我编写的代码

  /// <summary>
    /// Application Entry Point.
    /// </summary>
    [STAThread]
    [DebuggerNonUserCode]
    [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
    public static void Main()
    {
        // Get Reference to the current Process
        var thisProc = Process.GetCurrentProcess();
        // Check how many total processes have the same name as the current one
        if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
        {
            // the new application instance.
            Application.Current.Shutdown();
            foreach (var process in Process.GetProcessesByName(thisProc.ProcessName))
            {
                if(process.Id != thisProc.Id)
                {
                    // here i need to activate the main window of my one instance app.
                }                        
            }
            return;
        }
        var app = new App();
        app.InitializeComponent();
        app.Run();
    }

任何帮助将不胜感激。

4

1 回答 1

2

经过一番努力,我找到了解决方案,这是对我有用的代码

知道我在 wpf 上使用 mui 项目。

  public static class Win32 
    {
    //Import the FindWindow API to find our window
    [DllImport("User32.dll", EntryPoint = "FindWindow")]
    private static extern IntPtr FindWindowNative(string className, string windowName);
    //Import the SetForeground API to activate it
    [DllImport("User32.dll", EntryPoint = "SetForegroundWindow")]
    private static extern IntPtr SetForegroundWindowNative(IntPtr hWnd);
    public static IntPtr FindWindow(string className, string windowName)
    {
        return FindWindowNative(className, windowName);
    }
    public static IntPtr SetForegroundWindow(IntPtr hWnd)
    {
        return SetForegroundWindowNative(hWnd);
    }
}
internal class Program : Application
{
    private static void Activate(string title)
    {
        //Find the window, using the Window Title
        IntPtr hWnd = Win32.FindWindow(null, title);
        if (hWnd.ToInt32() > 0) //If found
        {
            Win32.SetForegroundWindow(hWnd); //Activate it
        }
    }

    [STAThread]
    [DebuggerNonUserCode]
    [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
    public static void Main()
    {
        // Get Reference to the current Process
        var thisProc = Process.GetCurrentProcess();
        // Check how many total processes have the same name as the current one
        if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
        {
            Activate("active dictionary");
            Current.Shutdown();
            return;
        }
        var app = new App();
        app.InitializeComponent();
        app.Run();
    }
}
于 2013-04-06T21:48:32.570 回答