将“this”参数传递给另一个类
本文关键字:另一个 参数传递 this | 更新日期: 2023-09-27 18:32:24
假设,我的表单没有边框,我将制作一个图像将是一个自定义标题栏
我想创建调用标题栏的类,有一个方法应用标题栏(控件 c);在项目中的任何表单中,只需调用 ApllyTitleBar() 到表单上的任何控件,当鼠标按下和鼠标移动时,表单也会移动。
类标题栏中的代码:
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 tb=new TitleBar();
tb.Apply(lblTitleBar);
我知道类 TitleBar 中的"this"参数不能有方法 Location() 和 PointToScreen(),因为"this"是 TitleBar 的实例,而不是 Form 的实例。有没有另一种方法可以将类传递给这个,或者那个方法???
tb.Apply(lblTitleBar,this);
我认为你在这里追求的是对该形式的引用:
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);
您可以尝试检索包含目标控件的窗体。
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;
}
}
}
}