2

我根本不是 Windows 开发人员(我做 AS3 的东西),但我在 Visual c# 2010 中编写了这个 C# 控制台应用程序以测试某些东西。该应用程序应该采用一个打开的窗口并调整其大小并重新定位它。

我打开了一个空白的 Chrome 窗口(标题为“无标题”),但控制窗口的功能不起作用(即使调试器在它们上停止 - 这意味着应用程序确实找到了正确的窗口)。

任何想法为什么?

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

namespace ConsoleApplication1
{
    class Program
    {


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

       [DllImport("user32.dll")]
       private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);


        static void Main(string[] args)
        {
            Process[] processlist = Process.GetProcesses();

            foreach (Process proc in processlist)
            {
                if (!String.IsNullOrEmpty(proc.MainWindowTitle) && proc.MainWindowTitle == "Untitled")
                {
                   ShowWindow(proc.Handle, 3);
                   MoveWindow(proc.Handle, 0, 0, 100, 100, true);
                }
            }


        }
    }
}
4

1 回答 1

7
   MoveWindow(proc.Handle, ...);

proc.Handle 不是你想象的那样。它是进程句柄,而不是您感兴趣的 Process.MainWindowHandle。

你问这个问题是因为你不检查错误。所以你不知道为什么它不起作用。这些函数返回bool, false 表示你弄错了。抛出一个 Win32Exception 所以这不是完全无法诊断的:

if (!MoveWindow(proc.MainWindowHandle, ...)) {
    throw new Win32Exception();
}
于 2013-06-19T13:44:17.293 回答