Winfrom 控件移位绘制垂直、水平线
public delegate void XMatchEventHandler(int x,bool flags);//定义委托
private int x;
///窗体加载
private void Form1_Load(object sender, EventArgs e)
{
XObject.p = this.panel1;
MatchListener ml = new MatchListener();
ml.XMatch += new MatchListener.XMatchEventHandler(ml_XMatch);
ThreadStart ts = new ThreadStart(ml.StratListen);
Thread t = new Thread(ts);
t.IsBackground = true;
t.Start();
}
void ml_XMatch(int x,bool flags)
{
this.Invoke(new XMatchEventHandler(myMathch), new object[] { x,flags });
}
void myMathch(int x,bool flags)
{
//Redr = flags;
XObject.Redr = false;
}
private int tempx;
private int tempy;
private bool flag = false;
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
tempx = e.X;
tempy = e.Y;
flag = true;
XObject.Redr = true;
this.panel2.Paint += new PaintEventHandler(Form1_Paint);
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (flag == true)
{
panel1.Location=(new Point(panel1.Location.X + e.X - tempx, panel1.Location.Y + e.Y - tempy));
}
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
flag = false;
XObject.Redr = false;
panel2.Refresh();
}
/// <summary>
/// 重绘控件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Form1_Paint(object sender, PaintEventArgs e)
{
if (XObject.Redr)
{
//BurlyWood CadetBlue Coral CornflowerBlue Cornsilk Crimson DarkBlue DarkCyan DarkGray
panel2.Refresh();
panel2.Update();
if (panel1.Location.X >= 3 || panel1.Location.X <= 3)
{
e.Graphics.DrawLine(new Pen(Color.DarkOrange, 2), new Point(panel1.Location.X, panel1.Parent.Location.Y), new Point(panel1.Location.X, panel1.Location.Y + Height));
}
if (panel1.Location.Y >= 3 || panel1.Location.Y <= 3)
{
e.Graphics.DrawLine(new Pen(Color.Orange, 2), new Point(0, panel1.Location.Y), new Point(panel1.Parent.Width, panel1.Location.Y));
}
XObject.Redr = false;
}
}
///静态类
public class XObject
{
public static System.Windows.Forms.Panel p;
public static bool Redr = false;
}
///侦听
public class MatchListener
{
public delegate void XMatchEventHandler(int x,bool flag);
public event XMatchEventHandler XMatch;
public void OnXMatch(int x,bool flag)
{
if (XMatch != null)
{
XMatch(x,flag);
}
}
public MatchListener() { }
public int X = 100;
public int Y = 100;
public void StratListen()
{
while (true)
{
if (Math.Abs(XObject.p.Left - X) < (XObject.p.Parent == null ? 200 : XObject.p.Parent.Width))
{
//OnXMatch(X,true);
XObject.Redr = true;
}
else
{
XObject.Redr = false;
}
System.Threading.Thread.Sleep(100);
}
}
}
注意:重绘时重要的方法Invalidate() Refresh() Update()