How to get and set the window position of another application in C#

怎甘沉沦 提交于 2019-11-26 04:41:33

问题


How can I get and set the position of another application using C#?

For example, I would like to get the top left hand coordinates of Notepad (let’s say it\'s floating somewhere at 100,400) and the position this window at 0,0.

What\'s the easiest way to achieve this?


回答1:


I actually wrote an open source DLL just for this sort of thing. Download Here

This will allow you to find, enumerate, resize, reposition, or do whatever you want to other application windows and their controls. There is also added functionality to read and write the values/text of the windows/controls and do click events on them. It was basically written to do screen scraping with - but all the source code is included so everything you want to do with the windows is included there.




回答2:


David's helpful answer provides the crucial pointers and helpful links.

To put them to use in a self-contained example that implements the sample scenario in the question, using the Windows API via P/Invoke (System.Windows.Forms is not involved):

using System;
using System.Runtime.InteropServices; // For the P/Invoke signatures.

public static class PositionWindowDemo
{

    // P/Invoke declarations.

    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll", SetLastError = true)]
    static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

    const uint SWP_NOSIZE = 0x0001;
    const uint SWP_NOZORDER = 0x0004;

    public static void Main()
    {
        // Find (the first-in-Z-order) Notepad window.
        IntPtr hWnd = FindWindow("Notepad", null);

        // If found, position it.
        if (hWnd != IntPtr.Zero)
        {
            // Move the window to (0,0) without changing its size or position
            // in the Z order.
            SetWindowPos(hWnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
        }
    }

}



回答3:


Try using FindWindow (signature) to get the HWND of the target window. Then you can use SetWindowPos (signature) to move it.




回答4:


You will need to use som P/Invoke interop to achieve this. The basic idea would be to find the window first (for instance, using the EnumWindows function), and then getting the window position with GetWindowRect.



来源:https://stackoverflow.com/questions/1364440/how-to-get-and-set-the-window-position-of-another-application-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!