Drawing on top of controls inside a panel (C# WinForms)

前端 未结 10 2265
暖寄归人
暖寄归人 2020-11-29 22:27

I know this question had been asked more than a few times, but so far I haven\'t been able to find a good solution for it.

I\'ve got a panel with other control on it

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 23:07

    Turns out this is a whole lot easier than I thought. Thanks for not accepting any of my other answers. Here is the two-step process for creating a Fline (floating line - sorry, it's late):

    Step 1: Add a UserControl to your project and name it "Fline". Add the following to the using statements:

    using System.Drawing.Drawing2D;
    

    Step 2: Add the following to the Fline's Resize event:

    int wfactor = 4; // half the line width, kinda
    // create 6 points for path
    Point[] pts = {
        new Point(0, 0), 
        new Point(wfactor, 0), 
        new Point(Width, Height - wfactor),
        new Point(Width, Height) ,
        new Point(Width - wfactor, Height),
        new Point(0, wfactor) };
    // magic numbers! 
    byte[] types = {
        0, // start point
        1, // line
        1, // line
        1, // line
        1, // line
        1 }; // line 
    GraphicsPath path = new GraphicsPath(pts, types);
    this.Region = new Region(path);
    

    Compile, and then drag a Fline onto your form or panel. Important: the default BackColor is the same as the form, so change the Fline's BackColor to Red or something obvious (in the designer). One weird quirk about this is that when you drag it around in the designer it shows as a solid block until you release it - not a huge deal.

    This control can appear in front of or behind any other control. If you set Enabled to false, it will still be visible but will not interfere with mouse events on the controls underneath.

    You'll want to enhance this for your purposes, of course, but this shows the basic principle. You can use the same technique for creating a control of whatever shape you like (my initial test of this made a triangle).

    Update: this makes a nice dense one-liner, too. Just put this in your UserControl's Resize event:

    this.Region=new Region(new System.Drawing.Drawing2D.GraphicsPath(new Point[]{new Point(0,0),new Point(4,0),new Point(Width,Height-4),new Point(Width,Height),new Point(Width-4,Height),new Point(0,4)},new byte[]{0,1,1,1,1,1}));
    

提交回复
热议问题