c# - 我如何聚焦外国窗口?

标签 c# .net focus

我有一个应用程序,它一次只能打开一个自身实例。为了强制执行此操作,我使用以下代码:

System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
foreach (System.Diagnostics.Process p in myProcesses)
{
    if (p.ProcessName == me.ProcessName)
        if (p.Id != me.Id)
        {
            //if already running, abort this copy.
            return;
        }
}
//launch the application.
//...

它工作正常。我还希望它能够聚焦已运行副本的形式。也就是说,在返回之前,我想把这个应用程序的另一个实例放到前台。

我该怎么做?

SetForegroundWindow 在某种程度上有效:

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

// ...
if (p.Id != me.Id)
{
    //if already running, focus it, and then abort this copy.
    SetForegroundWindow(p.MainWindowHandle);
    return;
}
// ...

如果窗口没有最小化,这会将窗口带到前台。惊人的。 但是,如果窗口被最小化,它将保持最小化状态。

它需要取消最小化。

通过 SwitchToThisWindow 的解决方案(有效!):

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

[STAThread]
static void Main()
{
    System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
    System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(me.ProcessName);
    foreach (System.Diagnostics.Process p in myProcesses)
    {
        if (p.Id != me.Id)
        {
            SwitchToThisWindow(p.MainWindowHandle, true);
            return;
        }
    }
    //now go ahead and start our application ;-)
}

最佳答案

我遇到了同样的问题 SwitchToThisWindow()对我来说效果最好。唯一的限制是您必须安装 XP sp1。我玩过 SetForegroundWindow、ShowWindow,它们都无法将窗口拉入 View 。

关于c# - 我如何聚焦外国窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52997955/

相关文章:

c# - 将 XML 加载到 XDocument 中的最快方法是什么?

javascript - .NET 中 Date.UTC 的类似物是什么

c# - 使用 Visual Studio Designer 在 TableLayoutPanel 中居中 Windows 窗体控件

.net - MEF类型 “AttributedAssemblyPartCatalog”发生了什么?

css - 输入焦点时更改背景位置 div

Java - 更改行为 Tab 键

javascript - 无法聚焦使用 JS 创建的输入

c# - 如何在 visual studio (C#) 中使用 webView 功能

c# - C# 中的缓存友好性

c# - 如何使用多线程管理连接和命令对象