C#中事件执行的先后循序问题...
- C# code
private void Form1_Load(object sender, EventArgs e) { Squer squer1 = new Squer(); squer1.startpoint.X = 50; squer1.startpoint.Y = 50; squer1.DrawSquer(this.pictureBox1.Handle); } private void pictureBox1_Paint(object sender, PaintEventArgs e) { Squer squer1 = new Squer(); squer1.startpoint.X = 50; squer1.startpoint.Y = 50; squer1.DrawSquer(this.pictureBox1.Handle); }
- C# code
class Squer { private Color bc_color = Color.Red; private int size = 50; public Point startpoint; public Squer() { } public void DrawSquer(System.IntPtr windowhandle) { Graphics g = Graphics.FromHwnd(windowhandle); SolidBrush b=new SolidBrush(Color.Red); g.FillRectangle(b, startpoint.X, startpoint.Y, size, size); } }
建一个winform窗体,里面放一个pictureBox执行上面的代码,为什么pictureBox中什么也没有...
[解决办法]
这个要用windows重绘事件啊
改动下代码
public void DrawSquer(System.IntPtr windowhandle, PaintEventArgs e)
{
Graphics g = Graphics.FromHwnd(windowhandle);
SolidBrush b=new SolidBrush(Color.Red);
g.FillRectangle(b, startpoint.X, startpoint.Y, size, size);
}
调用把事件对象 e 传进去,注意如果Picture控件在容器里,
squer1.DrawSquer(this.pictureBox1.Handle, e);
比如panel,父容器也要重绘,否则显示不出来
父
[解决办法]
注意,picture控件如果在容器里面。
比如panel,父容器也要重绘,否则显示不出来
[解决办法]
Graphics.FromHwnd事实上创建一个新的graphics,而不是传到paint 事件中的 Graphics 对象,因此在你在squer中画的 还没显示出来就被 默认的的盖住了。
解决该问题,两个办法。
1. 也就是最佳方法 用E.Graphics去画图。这是推荐的方法。
2. 用异步的方式去画,即是调用begininvoke。请看以下代码:
- C# code
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void pictureBox1_Paint(object sender, PaintEventArgs e) { Squer squer1 = new Squer(); squer1.startpoint.X = this.pictureBox1.Left; squer1.startpoint.Y = this.pictureBox1.Top; this.BeginInvoke((Action)(() => squer1.DrawSquer(this.pictureBox1.Handle))); } } class Squer { private Color bc_color = Color.Red; private int size = 50; public Point startpoint; public Squer() { } public void DrawSquer(System.IntPtr windowhandle) { Graphics g = Graphics.FromHwnd(windowhandle); SolidBrush b = new SolidBrush(Color.Red); g.FillRectangle(b, startpoint.X, startpoint.Y, size, size); } }