在C#中使用SetWindowPos来移动窗口 [英] Using SetWindowPos in C# to move windows around

查看:2427
本文介绍了在C#中使用SetWindowPos来移动窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code:

namespace WindowMover
{
    using System.Windows.Forms;

    static class Logic
    {
        [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
        public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);

        public static void Move()
        {
            const short SWP_NOMOVE = 0X2;
            const short SWP_NOSIZE = 1;
            const short SWP_NOZORDER = 0X4;
            const int SWP_SHOWWINDOW = 0x0040;

            Process[] processes = Process.GetProcesses(".");
            foreach (var process in processes)
            {
                var handle = process.MainWindowHandle;
                var form = Control.FromHandle(handle);

                if (form == null) continue;

                SetWindowPos(handle, 0, 0, 0, form.Bounds.Width, form.Bounds.Height, SWP_NOZORDER | SWP_SHOWWINDOW);
            }
        }
    }
}

这应该是我的桌面上每移动窗口,0,0(X,Y),并保持相同的尺寸。
我的问题是,只有调用应用程序(建于C#)是越来越移动。

This is supposed to move every window on my desktop to 0,0 (x,y) and keep the same sizes. My problem is that only the calling app (built in C#) is getting moved.

我应该使用比Control.FromHandle(IntPtr的)别的其他?这会不会只找DOTNET控件?如果是这样,我应该用什么呢?

Should I be using something else other than Control.FromHandle(IntPtr)? Will this only find dotnet controls? If so what should I use?

此外,在SetWindowPos二0只是一个随机INT我坚守在那里,我不知道用什么INT hWndInsertAfter

Also, the second 0 in SetWindowPos was just a random int I stick in there, I'm not sure what to use for int hWndInsertAfter

有关使用多个窗口像洋泾浜的流程是什么?

What about processes with multiple windows like pidgin?

推荐答案

只需拿出你的Control.FromHandle和形式== NULL检查。你应该能够只是做:

Just take out your Control.FromHandle and the form == null check. You should be able to just do:

IntPtr handle = process.MainWindowHandle;
if (handle != IntPtr.Zero)
{
    SetWindowPos(handle, 0, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
}

如果您添加SWP_NOSIZE,也不会改变窗口大小,但仍将重新定位。

If you add SWP_NOSIZE, it will not resize the window, but will still reposition it.

如果你想影响所有的窗口,而不仅仅是主窗口,每一个过程中,你可能要考虑使用的 EnumWindows的而不是HTML>的P / Invoke通过进程列表进行迭代,并使用MainWindowHandle。

If you want to effect all windows, not just the main window, of each process, you might want to consider using P/Invoke with EnumWindows instead of iterating through the Process list and using MainWindowHandle.

这篇关于在C#中使用SetWindowPos来移动窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆