首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SetForegroundWindow不工作

SetForegroundWindow不工作
EN

Stack Overflow用户
提问于 2014-05-07 00:27:55
回答 1查看 3.9K关注 0票数 3

我正在尝试启动一个应用程序,并将其放在最前面。然而,应用程序启动时是ok的,然后最终会落后于启动应用程序。请注意,在已经运行的最小化应用程序上使用类似的方法可以很好地工作(为简洁起见,从该示例中删除的代码)-只有在启动应用程序的新实例时才会失败。有什么想法吗?谢谢

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace Launcher
{
class Program
{
    [DllImport("User32.dll", SetLastError = true)]
    private static extern int SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);

    [DllImport("user32.dll")]
    private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

    private const           int    SW_SHOWMAXIMIZED = 3;

    private static readonly IntPtr HWND_TOP       = new IntPtr(0);
    private const           UInt32 SWP_NOSIZE     = 0x0001;
    private const           UInt32 SWP_NOMOVE     = 0x0002;
    private const           UInt32 SWP_SHOWWINDOW = 0x0040;

    static void Main(string[] args)
    {
            string wd = @"C:\Program Files (x86)\MyFolder";

            string fn = "MyApplication.exe";

            if (!System.IO.File.Exists(wd + @"\" + fn)) return;

            Process p = new Process();
            p.StartInfo.WorkingDirectory = wd;
            p.StartInfo.FileName = fn;

            p.StartInfo.CreateNoWindow = false;
            p.Start(); // app launches OK

            Thread.Sleep(5000);

            SetForegroundWindow(p.MainWindowHandle); // this has no effect
            SetWindowPos(p.MainWindowHandle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
        }
    }
}
}
EN

回答 1

Stack Overflow用户

发布于 2016-01-05 18:30:11

好的,在阅读了这里的更多问题后,我设法解决了这个问题,使用了WaitForInputIdle和一个do循环的组合,该循环检查要设置的窗口标题(这是我在代码中做的),以确保应用程序在调用SetForegroundWindow之前已经稳定下来。希望这能帮助其他人

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23500086

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档