Question

I am not a windows developer at all (i do AS3 stuff), but i wrote this C# console application in visual c# 2010 in order to test something. The app should take an open window and resize and reposition it.

i open a blank Chrome window (titled "Untitled"), but the functions controlling the window don't work (even though debugger stops on them - meaning the app did find the right window).

any ideas why?

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);
                }
            }


        }
    }
}
Was it helpful?

Solution

   MoveWindow(proc.Handle, ...);

proc.Handle is not what you think it is. It is the process handle, not the Process.MainWindowHandle that you are interested in.

You are asking this question because you don't check for errors. So you don't know why it doesn't work. These functions return bool, false means that you got it wrong. Throw a Win32Exception so this isn't completely undiagnosable:

if (!MoveWindow(proc.MainWindowHandle, ...)) {
    throw new Win32Exception();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top