在我自己的c#表单上运行扩展程序GUI

时间:2016-01-13 10:42:31

标签: c# forms firefox

我想编写一个与桌面相同的程序(如第二个桌面),我的意思是我想在浏览器进程上运行进程GUI,我想在我的表单上运行它。 我发现我可以使用User32.dll,我找到了代码。 这是代码:

private void LoadApplication(string path, IntPtr handle)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        int timeout = 10 * 1000;     // Timeout value (10s) in case we want to cancel the task if it's taking too long.

        Process p = Process.Start(path);

        //p.WaitForInputIdle();
        IntPtr Handle = new IntPtr();
        for (int i = 0; Handle == IntPtr.Zero && i < 300; i++)
        {
            Handle = p.MainWindowHandle;
            Thread.Sleep(10);
        }

        while (Handle == IntPtr.Zero)
        {
            System.Threading.Thread.Sleep(10);
            p.Refresh();

            if (sw.ElapsedMilliseconds > timeout)
            {
                sw.Stop();
                return;
            }
        }

        SetParent(Handle, handle);      // Set the process parent window to the window we want
        SetWindowPos(Handle, 0, 0, 0, 0, 0, 0x0001 | 0x0040);       // Place the window in the top left of the parent window without resizing it
    }

如果我使用cmd,Internet Explorer甚至记事本的路径运行该代码它工作正常,但是当我尝试使用firefox或calc.exe运行它时,它打开程序但不在我的表单上 - 在资源管理器上。可执行程序 也许我做错了什么?或者还有其他方法可以按我的意愿做“虚拟桌面”?

感谢名单

1 个答案:

答案 0 :(得分:0)

我找到了解决方案!!!!运行程序后,将线程休眠+ -3000秒,然后像我一样运行代码:

private void LoadApplication(string path, IntPtr handle)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        int timeout = 10 * 1000;     // Timeout value (10s) in case we want to cancel the task if it's taking too long.
        Process p = Process.Start(path);
        Thread.Sleep(3000);
        Process[] proc = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(path));
        for(int j = 0 ;j<proc.Length;j++)
        {
            p = proc[j];
            //p.WaitForInputIdle();
            IntPtr Handle = new IntPtr();
            Handle = p.MainWindowHandle;
            if(Handle == IntPtr.Zero)
            {
                continue;
            }

            while (Handle == IntPtr.Zero)
            {
                System.Threading.Thread.Sleep(10);
                p.Refresh();

                if (sw.ElapsedMilliseconds > timeout)
                {
                    sw.Stop();
                    return;
                }
            }

            SetParent(Handle, handle);      // Set the process parent window to the window we want

        }

    }