场景:
点击按钮,隐藏界面上的控件,然后在paint 里面输出提示信息。
如题
代码如下:
private void cbxCoverSub_CheckedChanged(object sender, EventArgs e)
{
bool bShow = !cbxCoverSub.Checked;
showSubtitle(bShow);
showNotice();
}
两个函数的代码如下:
private void showSubtitle(bool bShow)
{
txtBackSubtitle.Visible = bShow;
txtTopSubtitle.Visible = bShow;
}
这段代码用于更新提示信息
private void showNotice()
{
string str = "You can move and adjust this bar with mouse to cover the hard subtitle.";
Graphics g = this.CreateGraphics();//
Pen p = new Pen(Color.Blue, 2);//定义了一个蓝色,宽度为的画笔
SolidBrush brsh = new SolidBrush(m_mouseMvBkClr);
// clear the background
g.FillRectangle(brsh, this.ClientRectangle);
// measure the length of the string in pixel
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
Size size = TextRenderer.MeasureText(str, this.Font);
Rectangle rect = new Rectangle((this.Width - pnlRight.Width) / 2 - size.Width / 2, (this.Height - size.Height) / 2, size.Width, size.Height);
TextRenderer.DrawText(g, str, this.Font, rect, Color.Yellow, m_mouseMvBkClr);
//draw a border for this form
g.DrawRectangle(p, this.ClientRectangle);
}
paint 事件中:
private void showSubForm_Paint(object sender, PaintEventArgs e)
{
//draw a border that the user can see the border of this form
if (cbxCoverSub.Checked){
showNotice();
}
//g.DrawEllipse(p, 10, 10, 100, 100);//在画板上画椭圆,起始坐标为(10,10),外接矩形的宽为,高为
}
一切看似乎完美,然而,期待的画面没有出现,必须手动刷新才得到期待的结果:
尝试 Refreash,无效;
后来深度怀疑是visible 属性引发了一个貌似滞后的消息,即这个隐藏行为发生在paint之后,因此,paint感觉好像没有执行。弄了个timer测试了一些,发现可以得到预想界面。但是这样显然不是正解,忽然想到,控件的显示和隐藏函数应该是阻塞方式,于是将代码改了一下,即
private void showSubtitle(bool bShow)
{
//pay attention of the following code
// it seems that Visible = true will trigger the system to send a a message and it will take effect after the paint event
// that makes the codes in paint event run before the control response to this message.
if (bShow)
{
//txtBackSubtitle.Visible = bShow;
//txtTopSubtitle.Visible = bShow;
txtBackSubtitle.Show();
txtTopSubtitle.Show();
}
else
{
txtBackSubtitle.Hide();
txtTopSubtitle.Hide();
}
this.Refresh();
}
马拉孙于2021-01-24
海淀泛五道口地区