为什么设置双缓冲后,启动程序后不显示g.drawstring的内容,用鼠标在窗口滑动后才显示g.drawstring的内容。是什么地方出了问题
单应矩阵 2021-05-26 09:56:15 class DisplayTextForm : Form
{
public struct TextInfo
{
public string[] displayText;
public Rectangle[] rect;
}
[DllImport("user32", EntryPoint = "SetLayeredWindowAttributes")]
private static extern int SetLayeredWindowAttributes(IntPtr hwnd, int crKey, int bAlpha, int dwFlags);
[DllImport("user32", EntryPoint = "SetWindowLong")]
private static extern uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);
private TextInfo textInfos = new TextInfo();
private Label label1;
private int mouseFlag = -1;
public DisplayTextForm(string[] displayText,Form parentForm)
{
this.Size = new Size(300, 300);
this.Location = new Point(100, 100);
this.BackColor = Color.Red;
this.Show();
this.textInfos.displayText = displayText;
this.textInfos.rect = new Rectangle[5];
this.Paint += new System.Windows.Forms.PaintEventHandler(this.DisplayTextForm_Paint);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.DisplayTextForm_MouseDown);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.DisplayTextForm_MouseMove);
this.DoubleBuffered = true;//设置本窗体
Invalidate();
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
}
private void DisplayTextForm_Paint(object sender, PaintEventArgs e)
{
Draw();
}
public void Draw()
{
if (textInfos.displayText == null || textInfos.rect == null)
{
return;
}
Point textPos = new Point(0, 0);
using (Graphics g = this.CreateGraphics())
{
g.PageUnit = GraphicsUnit.Pixel;
g.SmoothingMode = SmoothingMode.HighQuality;
StringFormat sf = new StringFormat();
sf.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
for (int i = 0; i < textInfos.displayText.Length; i++)
{
textPos = new Point(0, i * 20);
Font font = new Font("宋体", 10);
SizeF sizeF = g.MeasureString(textInfos.displayText[i], font, 500, sf);
Size size = System.Drawing.Size.Ceiling(sizeF);
textInfos.rect[i] = new Rectangle(textPos, size);
g.DrawRectangle(new Pen(Brushes.Black), new Rectangle(textPos, size));
if(mouseFlag != -1)
{
if (lastflag == mouseFlag) return;
g.FillRectangle(Brushes.Gray, textInfos.rect[mouseFlag]);
lastflag = mouseFlag;
}
g.DrawString(textInfos.displayText[i], font, Brushes.Black, textPos);
}
}
}
private int lastflag = -2;
private void DisplayTextForm_MouseMove(object sender, MouseEventArgs e)
{
Point mousePoint = e.Location;
for(int i = 0; i< textInfos.rect.Length; i++)
{
if(textInfos.rect[i].Contains(mousePoint))
{
mouseFlag = i;
Invalidate(textInfos.rect[i]);
}
}
}