无论如何可以控制可以移动表单的位置吗?
所以如果我移动一个表格,它只能在垂直轴上移动,当我尝试水平移动它时,什么也没有发生。
我不想要像 locationchanged 或 move 事件这样的错误实现并将其弹出回内联。我没有办法使用 WndProc 覆盖之类的东西,但搜索了一段时间后,我找不到任何东西。请帮忙
无论如何可以控制可以移动表单的位置吗?
所以如果我移动一个表格,它只能在垂直轴上移动,当我尝试水平移动它时,什么也没有发生。
我不想要像 locationchanged 或 move 事件这样的错误实现并将其弹出回内联。我没有办法使用 WndProc 覆盖之类的东西,但搜索了一段时间后,我找不到任何东西。请帮忙
例如:
using System.Runtime.InteropServices;
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x216) // WM_MOVING = 0x216
{
Rectangle rect =
(Rectangle) Marshal.PtrToStructure(m.LParam, typeof (Rectangle));
if (rect.Left < 100)
{
// compensates for right side drift
rect.Width = rect.Width + (100 - rect.Left);
// force left side to 100
rect.X = 100;
Marshal.StructureToPtr(rect, m.LParam, true);
}
}
base.WndProc(ref m);
}
上面的代码将最小左手位置设置为 100。
不需要像 driis 那样重新创建 RECT 结构,.NET 原生 Rectangle 可以正常工作。但是,您必须通过 X 属性设置位置,因为 Left 是仅限获取的属性。
您很可能想要覆盖 WndProc 并处理 WM_MOVING 消息。根据 MSDN:
WM_MOVING 消息被发送到用户正在移动的窗口。通过处理此消息,应用程序可以监视拖动矩形的位置,并在需要时更改其位置。
这将是一种方法,但是,您显然需要根据需要对其进行调整:
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace VerticalMovingForm
{
public partial class Form1 : Form
{
private const int WM_MOVING = 0x0216;
private readonly int positionX;
private readonly int positionR;
public Form1()
{
Left = 400;
Width = 500;
positionX = Left;
positionR = Left + Width;
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_MOVING)
{
var r = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));
r.Left = positionX;
r.Right = positionR;
Marshal.StructureToPtr(r, m.LParam, false);
}
base.WndProc(ref m);
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
}
}
VB.NET 版本:
Protected Overloads Overrides Sub WndProc(ByRef m As Message)
If m.Msg = &H216 Then
' WM_MOVING = 0x216
Dim rect As Rectangle = DirectCast(Marshal.PtrToStructure(m.LParam, GetType(Rectangle)), Rectangle)
If rect.Left < 100 Then
' compensates for right side drift
rect.Width = rect.Width + (100 - rect.Left)
' force left side to 100
rect.X = 100
Marshal.StructureToPtr(rect, m.LParam, True)
End If
End If
MyBase.WndProc(m)
End Sub