假设我的表格没有BORDER,我会将图片设为自定义标题栏
我想创建调用TitleBar的类,有一个方法ApplyTitleBar(Control c); 在项目的任何Form中,只需将ApllyTitleBar()调用到Form上的任何Control,当鼠标向下移动并移动鼠标时,Form也会移动。
TitleBar类中的代码:
public class TitleBar
{
private bool drag = false; // determine if we should be moving the form
private Point startPoint = new Point(0, 0);
public void ApplyTitleBar(Control c)
{
c.MouseUp += new MouseEventHandler(panelTitleBar_MouseUp);
c.MouseMove += new MouseEventHandler(panelTitleBar_MouseMove);
c.MouseDown += new MouseEventHandler(panelTitleBar_MouseDown);
}
void panelTitleBar_MouseUp(object sender, MouseEventArgs e)
{
this.drag = false;
}
void panelTitleBar_MouseDown(object sender, MouseEventArgs e)
{
this.startPoint = e.Location;
this.drag = true;
}
void panelTitleBar_MouseMove(object sender, MouseEventArgs e)
{
if (this.drag)
{ // if we should be dragging it, we need to figure out some movement
Point p1 = new Point(e.X, e.Y);
Point p2 = this.PointToScreen(p1);
Point p3 = new Point(p2.X - this.startPoint.X,
p2.Y - this.startPoint.Y);
this.Location = p3;
}
}
}
假设在另一个表单中,我有标签lblTitleBar并希望它将是“titleBar”
TitleBar tb=new TitleBar();
tb.Apply(lblTitleBar);
我知道TitleBar类中的“this”参数不能有方法Location()和PointToScreen(),因为“this”是TitleBar的实例,而不是Form的实例。 是否有另一种方法可以将类传递给它,或者是这样做的方式???
tb.Apply(lblTitleBar,this);
答案 0 :(得分:0)
我认为您在此之后的内容是对表格的引用:
public class TitleBar
{
private bool drag = false; // determine if we should be moving the form
private Point startPoint = new Point(0, 0);
private Form form;
public void ApplyTitleBar(Control c, Form f)
{
c.MouseUp += new MouseEventHandler(panelTitleBar_MouseUp);
c.MouseMove += new MouseEventHandler(panelTitleBar_MouseMove);
c.MouseDown += new MouseEventHandler(panelTitleBar_MouseDown);
this.form = f;
}
....
然后你可以这样做:
void panelTitleBar_MouseMove(object sender, MouseEventArgs e)
{
if (this.drag)
{ // if we should be dragging it, we need to figure out some movement
Point p1 = new Point(e.X, e.Y);
Point p2 = form.PointToScreen(p1);
Point p3 = new Point(p2.X - form.startPoint.X,
p2.Y - form.startPoint.Y);
form.Location = p3;
}
}
并且,假设您从 表单中实例化所有这些,您确实会这样称呼它:
tb.ApplyTitleBar(lblTitleBar,this);
答案 1 :(得分:0)
您可以尝试检索包含目标控件的表单。
void panelTitleBar_MouseMove(object sender, MouseEventArgs e)
{
Control control = sender as Control;
if(null != control)
{
Form form = control.FindForm();
if(null != form)
{
if (this.drag)
{ // if we should be dragging it, we need to figure out some movement
Point p1 = new Point(e.X, e.Y);
Point p2 = form.PointToScreen(p1);
Point p3 = new Point(p2.X - this.startPoint.X,
p2.Y - this.startPoint.Y);
form.Location = p3;
}
}
}
}