Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

c# - How to check if process started with ShellExecute is launched?

I'm writing a program to open several links and paths in new windows and put them to certain spots on a certain screen.

Until now I use the code below:

class Program
{
    [DllImport("shell32.dll", EntryPoint = "ShellExecute")]
    public static extern long ShellExecute(int hwnd, string cmd, string file, string param1, string param2, int swmode);

    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
    public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);


    static void Main(string[] args)
    {
        IntPtr hwnd;

        ShellExecute(0, "open", "C:\Program Files\Mozilla Firefox\firefox.exe", "www.example.de", "", 5);
        Thread.Sleep(5000);
        hwnd = GetForegroundWindow();
        SetWindowPos(hwnd, 0, 0, 0, 960, 1080, 0);

        //and so on for 8 applications on 4 screens...
    }
}

I used the ugly sleep command because it takes some time for this old Computer to open the URL or application.

Is there a way to check if the window is open yet? So the program only proceeds when the Window is already there.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could also look into setting commandline switches of the specific browser and skip the P/Invoke. Here is an example for Google Chrome:

[STAThread]
static void Main()
{
    OpenUrl("www.example.com")
        .ContinueWith((lastTask) =>
            OpenUrl("www.example.de")
        ).ContinueWith((lastTask) =>
            OpenUrl("www.google.com")
        ).ContinueWith((lastTask) =>
            OpenUrl("www.stackoverflow.com")
        ).Wait();
}

private static Task OpenUrl(string url)
{
    return Task.Run(() =>
    {
        var chromePath = @"C:Program Files (x86)GoogleChromeApplicationchrome.exe";

        var startInfo = new ProcessStartInfo(chromePath, $"--user-data-dir=a --window-position=2400,400 --window-size=500,500 --app="http://{url}"");
        var process = Process.Start(startInfo);

        process.WaitForInputIdle();
    });
}

Where we set the window-position and window-size as an argument to the ProcessStartInfo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...