日期:2014-05-19  浏览次数:20904 次

winform在程序运行中,鼠标选中控件,控件呈选中状态,并能拖动拖动鼠标改变控件大小和位置,如从工具箱中创建控件一样的效果,最好提供
winform在程序运行中,鼠标选中控件,控件呈选中状态,并能拖动拖动鼠标改变控件大小和位置,如从工具箱中创建控件一样的效果,最好提供代码


------解决方案--------------------
用如下的代码可以生成一个可以移动并调整大小的UserControl,可以把代码添加到一个Window应用程序中,编译项目,然后打开一个Form设计窗体向其添加MoveableControl类型的控件,运行程序可以用鼠标来调整这个控件了,任何一个窗口类型的类都可以做为这个类的基类,比如Button,Panel,PictureBox, ListBox等等,都可以:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace someTest
{
class MoveableControl:UserControl
{
internal static int WM_NCHITTEST = 0x84; //移动鼠标,按住或释放鼠标时发生的系统消息
internal static int WM_NCACTIVATE = 0x86;//窗体的激活状态发生改变的消息

internal static IntPtr HTCLIENT = (IntPtr)0x1;//工作区
internal static IntPtr HTSYSMENU = (IntPtr)3;//系统菜单
internal static IntPtr HTCAPTION = (IntPtr)0x2; //标题栏

internal static IntPtr HTLEFT = (IntPtr)10;//向左
internal static IntPtr HTRIGHT = (IntPtr)11;//向右
internal static IntPtr HTTOP = (IntPtr)12;//向上
internal static IntPtr HTTOPLEFT = (IntPtr)13;//向左上
internal static IntPtr HTTOPRIGHT = (IntPtr)14;//向右上
internal static IntPtr HTBOTTOM = (IntPtr)15;//向下
internal static IntPtr HTBOTTOMLEFT = (IntPtr)16;//向左下
internal static IntPtr HTBOTTOMRIGHT = (IntPtr)17;//向右下

private int m_BorderWidth = 4;
private bool m_Sizeable = true;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_NCHITTEST)
{
base.WndProc(ref m);
if (DesignMode)
{
return;
}
if (m.Result == HTCLIENT)
{
m.HWnd = this.Handle;

System.Drawing.Rectangle rect = this.RectangleToScreen(this.ClientRectangle);
Point C_Pos = Cursor.Position;
if ((C_Pos.X <= rect.Left + m_BorderWidth) && (C_Pos.Y <= rect.Top + m_BorderWidth) && this.m_Sizeable)
m.Result = HTTOPLEFT;//左上
else if ((C_Pos.X > = rect.Left + rect.Width - m_BorderWidth) && (C_Pos.Y <= rect.Top + m_BorderWidth) && this.m_Sizeable)
m.Result = HTTOPRIGHT;//右上
else if ((C_Pos.X <= rect.Left + m_BorderWidth) && (C_Pos.Y > = rect.Top + rect.Height - m_BorderWidth) && this.m_Sizeable)
m.Result = HTBOTTOMLEFT;//左下
else if ((C_Pos.X > = rect.Left + rect.Width - m_BorderWidth) && (C_Pos.Y > = rect.Top + rect.Height - m_BorderWidth) && this.m_Sizeable)
m.Result = HTBOTTOMRIGHT;//右下
else if ((C_Pos.X <= rect.Left + m_BorderWidth - 1) && this.m_Sizeable)
m.Result = HTLEFT;//左
else if ((C_Pos.X > = rect.Left + rect.Width - m_BorderWidth) && this.m_Sizeable)
m.Result = HTRIGHT;//右
else if ((C_Pos.Y <= rect.Top + m_BorderWidth - 1) && this.m_Sizeable)
m.Result = HTTOP;//上
else if ((C_Pos.Y > = rect.Top + rect.Height - m_BorderWidth) && this.m_Sizeable)
m.Result = HTBOTTOM;//下
else
{
m.Result = HTCAPTION;//模拟标题栏,移动或双击可以最大或最小化窗体
}
}
return;
}
base.WndProc(ref m);
}
}
}