打开进程并更改窗口位置

16

我希望能够在C#中打开一个应用程序(独立的Flash播放器),并将其位置设置为屏幕上的(0,0)。我该怎么做?到目前为止,我已经成功地打开了Flash播放器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace swflauncher
{
    class Program
    {
        static void Main(string[] args)
        {
            Process flash = new Process();
            flash.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

            flash.StartInfo.FileName = "D:\\development\\flex4\\runtimes\\player\\10\\win\\FlashPlayer.exe";
            flash.Start();
        }
    }
}
3个回答

52

谢谢大家,它现在可以工作了!:)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace swflauncher
{
    class Program
    {
        static void Main(string[] args)
        {
            Process flash = new Process();
            flash.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

            flash.StartInfo.FileName = "D:\\development\\flex4\\runtimes\\player\\10\\win\\FlashPlayer.exe";
            flash.Start();
            Thread.Sleep(100);

            IntPtr id = flash.MainWindowHandle;
            Console.Write(id);
            Program.MoveWindow(flash.MainWindowHandle, 0, 0, 500, 500, true);
        }

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);


    }
}

19
非常感谢您分享可工作的代码,这比答案好多了。 - u8it
我在StartInfo中使用文档名称而不是可执行文件名称。使用Paint和StartInfo.FileName中的.jpg参数也可以正常工作。但是,当FileName中包含任何MIME类型时,代码将不起作用。当MIME类型为图像格式且要使用标准Windows 10图片查看器“Photos”打开时,程序会在MoveWindow调用上导致异常“没有与此对象关联的进程”。 - Goodies
1
与其使用 Thread.Sleep(100),使用 flash.WaitForInputIdle() 更好地获取 MainWindowHandle - Kae10

7

启动Process后,它的MainWindowHandle属性应该被设置为一些Windows句柄,可用于操作已启动应用程序的主窗口。我认为没有一种直接使用.NET API移动它的方法,但可以通过P/Invoke使用MoveWindow API函数。

以下是一些链接,您可以在其中找到更多信息:


2
Process.WaitForInputIdle()将会非常重要。 - Hans Passant

4

尝试使用描述此处SetWindowPos这个页面展示了如何从C#调用它。


7
答案不够好因为没有提供可工作的代码。此外,展示如何从C#调用它的页面混乱不清,并且没有提供一个完整运行的例子(未知方法GetActiveWindowHandle)。作者下面的回答更好,简洁实用。 - Tyler Forsythe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接