我试图让form2相对于form1定位。我尝试过很多东西似乎没什么用。我想尝试一下:
http://www.pinvoke.net/default.aspx/user32/MoveWindow.html
作为Windows编程的新手,特别是C#我正在查看语法/示例,我发现很难知道要为参数添加什么。我确实得到了一个更简单的p / invoke来工作:
using System.Runtime.InteropServices;
...
public partial class Form1 : Form
{
public Form1()
{ InitializeComponent(); }
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CreateDirectory(string lpPathName,
IntPtr lpSecurityAttributes);
private void Form1_Load(object sender, EventArgs e) { }
private void button1_Click(object sender, EventArgs e)
{ CreateDirectory(@"c:\test4", IntPtr.Zero); }
}
...
我正在猜测IntPtr是"说"我指着第一个节点 - 但只是一个猜测......
MoveWindow的C#签名:
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
在网站上也有这方面的评论。 " IntPtr hWnd" - 我需要将其与Form2(?)相关联,重新绘制吗?我试图表明我已经看过它并试图解决它 - 我知道我们是从系统中得到它的......我得到的xy但是得到了它"与" Form2我输了。帮助赞赏。
答案 0 :(得分:2)
一般来说,你不需要像这样简单的PInvoke。
只要您从form1引用form2,就可以通过监听form1的LocationChanged
事件轻松完成此操作。当form1移动时,您可以通过执行以下操作来移动form2:
var location = this.Location;
location.Offset(xoffset, yoffset);
form2.Location = location;
这通常足以确保将form2放在相对于form1的某个位置,并在移动form1时更新其位置。如果在首次创建表单时未调用LocationChanged
事件,则可能必须设置form2的初始位置。
答案 1 :(得分:1)
这样的事情应该有效。测试过了。你可以改变它以完全符合你想要做的事情,这根本不应该是一个问题。
// Win32 RECT
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
// GetWindowRect gets the win32 RECT by a window handle.
[DllImport("user32.dll", SetLastError=true)]
static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
// MoveWindow moves a window or changes its size based on a window handle.
[DllImport("user32.dll", SetLastError = true)]
static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
// MoveForms moves one form to another using the win api.
void MoveForms(Form fromForm, Form toForm)
{
IntPtr hWnd_from = fromForm.Handle; // fromForm window handle
IntPtr hWnd_to = toForm.Handle; // toForm window handle
RECT rect_from, rect_to; // RECT holders for fromForm and toForm
if (GetWindowRect(hWnd_from, out rect_from) &&
GetWindowRect(hWnd_to, out rect_to)) // if it gets the win32 RECT for both the fromForm and toForm do the following ...
{
int x_to = rect_to.Left; // toForm's X position
int y_to = rect_to.Top; // toForm's Y position
int width_from = rect_from.Right - rect_from.Left; // fromForm's width
int height_from = rect_from.Bottom - rect_from.Top; // fromForm's height
// Moves fromForm to toForm using the x_to, y_to for X/Y and width_from, height_from for W/H.
MoveWindow(hWnd_from, x_to, y_to, width_from, height_from, true);
}
}