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
Yes, this can be done. The problem is that the panel and the controls on it are all separate windows (in the API sense), and thus all separate drawing surfaces. There is no one drawing surface to draw on to get this effect (other than the top-level screen surface, and it's considered impolite to draw all over that).
The (cough-hack-cough) trick is to draw the line on the panel underneath the controls, and also draw it on each of the controls themselves, resulting in this (which will persist even when you click the buttons and move the mouse around):
Create a winforms project (which should come with Form1 by default). Add a panel (named "panel1") and two buttons ("button1" and "button2") on the panel as shown. Add this code in the form's constructor:
panel1.Paint += PaintPanelOrButton;
button1.Paint += PaintPanelOrButton;
button2.Paint += PaintPanelOrButton;
and then add this method to the form's code:
private void PaintPanelOrButton(object sender, PaintEventArgs e)
{
// center the line endpoints on each button
Point pt1 = new Point(button1.Left + (button1.Width / 2),
button1.Top + (button1.Height / 2));
Point pt2 = new Point(button2.Left + (button2.Width / 2),
button2.Top + (button2.Height / 2));
if (sender is Button)
{
// offset line so it's drawn over the button where
// the line on the panel is drawn
Button btn = (Button)sender;
pt1.X -= btn.Left;
pt1.Y -= btn.Top;
pt2.X -= btn.Left;
pt2.Y -= btn.Top;
}
e.Graphics.DrawLine(new Pen(Color.Red, 4.0F), pt1, pt2);
}
Something like this needs to be drawn in each control's Paint event in order for the line to persist. It's easy to draw directly on controls in .NET, but whatever you draw is wiped away when someone clicks the button or moves the mouse over it (unless it's perpetually redrawn in the Paint events, as here).
Note that for this to work, any control drawn over has to have a Paint event. I'm sure you will have to modify this sample to achieve what you need. If you come up with a good generalized function for this, please post it.
Update: this method will not work for scrollbars, textboxes, comboboxes, listviews, or basically anything with a textbox-type thing as part of it (and not because it only offsets for buttons in the example above - you just can't draw on top of a textbox at all, at least not from its Paint event, at least not if you're me). Hopefully that won't be a problem.