set panel border thickness in c# winform

岁酱吖の 提交于 2019-11-29 22:46:07

问题


I have searching and the result cannot solve my case. Actually I have a panel and I want the panel have thicker border than Windows given. I need BorderStyle

BorderStyle.FixedSingle

thicker.. Thanks before


回答1:


You have to customize your own Panel with a little custom painting:

//Paint event handler for your Panel
private void panel1_Paint(object sender, PaintEventArgs e){ 
  if(panel1.BorderStyle == BorderStyle.FixedSingle){
     int thickness = 3;//it's up to you
     int halfThickness = thickness/2;
     using(Pen p = new Pen(Color.Black,thickness)){
       e.Graphics.DrawRectangle(p, new Rectangle(halfThickness,
                                                 halfThickness,
                                                 panel1.ClientSize.Width-thickness,
                                                 panel1.ClientSize.Height-thickness));
     }
  }
}

Here is the screen shot of panel with thickness of 30:

NOTE: The Size of Rectangle is calculated at the middle of the drawing line, suppose you draw line with thickness of 4, there will be an offset of 2 outside and 2 inside.

I didn't test the case given by Mr Hans, to fix it simply handle the event SizeChanged for your panel1 like this:

private void panel1_SizeChanged(object sender, EventArgs e){
   panel1.Invalidate();
}

You can also setting ResizeRedraw = true using Reflection without having to handle the SizeChanged event as above like this:

typeof(Control).GetProperty("ResizeRedraw", BindingFlags.NonPublic | BindingFlags.Instance)
               .SetValue(panel1, true, null);

You may see a little flicker when resizing, just add this code to enable doubleBuffered for your panel1:

typeof(Panel).GetProperty("DoubleBuffered",
                          BindingFlags.NonPublic | BindingFlags.Instance)
             .SetValue(panel1,true,null);



回答2:


Create a new, slightly larger panel and set the background colour to Black (or whatever). Place the original panel INSIDE the larger panel.



来源:https://stackoverflow.com/questions/19163809/set-panel-border-thickness-in-c-sharp-winform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!