C#窗体控件移动
问题描述:
无论如何要控制你可以移动窗体的位置吗?C#窗体控件移动
所以,如果我移动一个窗体,它只能在垂直轴上移动,当我尝试水平移动它时,什么都不会发生。
我不想像位置改变或移动事件并将其弹回内联的bug的实现。我不知道有什么方法使用像WndProc覆盖的东西,但搜索一段时间后,我找不到任何东西。请帮忙
答
你很可能想覆盖WndProc并处理WM_MOVING消息。 According to MSDN:
WM_MOVING消息发送到用户正在移动的 窗口。通过 处理此消息, 应用程序可以监视拖动矩形的位置 ,如果需要, 更改其位置。
这将是一个办法做到这一点,但是,你显然需要tweek它为您的需求:
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;
}
}
}
答
例如:
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.
没有必要重新创建RECT结构,就像driis那样,.NET原生Rectangle工作正常。但是,您必须通过X属性设置位置,因为Left是Get only属性。
答
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
+1使用尽可能多的本地CLR代码越好。 – 2009-06-01 00:16:34