Borderless Winform with a 1px border - c#

This might sound like a weird question but I have C# Winform that I set the FormBorderStyle to None. So far everything is good but I was wondering if there was a way to add like a 1px border on around my form ? I know I could do it by creating my own image but I was wondering if there was a more natural way of doing it.
Thanks

I consider using an image, or creating unnecessary controls for something that is easily paintable using GDI+ a waste of resources.
I think the simplest solution is overriding the OnPaint method of your form and drawing the border yourself:
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawRectangle(Pens.Black, this.Bounds);
}
Of course, you may also use your own Pen with your own color and width.

Use padding 1;1;1;1 to your form and set a background color to your form, and put a panel to your form. Set white or other normal background color to the panel. And set dock in parent controller. The background color of the form will act as a border.

How about just adding a Panel (and setting it's border) to the Form?

Thanks for the suggestions, I've decided to create 4 1px label and just toss on the edge on each side. That way:
1. They are minding their own business on the side rather than taking up the whole middle if you use use a groupbox or panel.
2. You are able to choose change your border color.

There is no more natural or non natural ways to do it. It depends on what you want.
If you put a background image on the form, you have to consider a fact that in order to be able to support resizable for you have to have resizable background images.
If you simply draw on the background with a Pen or Brush, you can support also resizable form, but you have to work more if you want to do something cool, instead with image it's easier.
You can embed some control inside the form and with color's of them make a feeling of the border. Like control, you can use Panel, as suggested in comment, can use GroupBox that creates thin broder arround, or something else.

I created this method, so you could easily set the borderposition, color and thickness.
private void customBackgroundPainter(PaintEventArgs e, int linethickness = 2, Color linecolor = new Color(), int offsetborder = 6)
{
Rectangle rect = new Rectangle(offsetborder, offsetborder, this.ClientSize.Width - (offsetborder * 2), this.ClientSize.Height - (offsetborder * 2));
Pen pen = new Pen(new Color());
pen.Width = linethickness;
if (linecolor != new Color())
{
pen.Color = linecolor;
}
else
{
pen.Color = Color.Black;
}
e.Graphics.DrawRectangle(pen, rect);
}
You could use it in the OnPaintBackground likes this:
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
customBackgroundPainter(
e,
linethickness: 3,
linecolor: Color.DarkOrange,
offsetborder: 5
);
}

Related

C# NET - Draw opaque brush on form with opacity level set

What I want to achieve is a semi-transparent background that covers the screen.
And then be able to draw non-transparent brushes on top of it.
What I have tried is to have a form with the size of the screen, then setting it's color and setting this.opacity = 0.5. However this affects all brushes in the form.
Ive also tried setting the background color to Color.Transparent, and then drawing an additional brush that covers the screen with opacity 0.5 before I then draw the opaque brushes... However the background becomes opaque as well.
Even though the style flag is set (ControlStyles.SupportsTransparentBackColor, true)
I know I can achieve this by having an additional form.
One form for the transparent background and one for the opaque foreground, but isn't that overkill?
Is there a better way?
Update 1:
Trying what is suggested in the comments.
Current state:
Form1: the main program, calls for the 'overlay' to show, which is:
Form2: Overlay background (semi-transparent black) and,
Form3: Overlay foreground, this is where the user draws.
Form 1 and 2 works as indended, however Form3 refuses to work with transparency.
If I set
this.BackColor = Color.Lime;
this.TransparencyKey = Color.Lime;
then the performance drops and the program lags heavily (although it does become transparent).
Ideally I would want to use this.BackColor = Color.Transparent; however that doesn't have any effect (solid background, no alpha).
Note that the form covers the screen and the background is usually the desktop. Maybe that's why it doesn't work?
You can override the OnPaintBackground of the form, without calling it's base.
This will enable you to specify whatever color you want for the background.
Try this:
protected override void OnPaintBackground(PaintEventArgs e)
{
using (var brush = new SolidBrush(Color.FromAgrb(50, 0, 0, 0))
{
e.Graphics.FillRectangle(brush, e.ClipRectangle);
}
}

How to make a UserControls BackColor transparent in C#?

I created a simple stick man in a Windows Form User-Control (consisting of a radio button and three labels and one progress bar).
I set the back-color of the new user-control to transparent so that when I drag it onto my form, it blends with other colors and drawings on the form.
I am not getting what I'm trying to achieve.
Here is the picture:
UserControl already supports this, its ControlStyles.SupportsTransparentBackColor style flag is already turned on. All you have to do is set the BackColor property to Color.Transparent.
Next thing you have to keep in mind in that this transparency is simulated, it is done by asking the Parent of the control to draw itself to produce the background. So what is important is that you get the Parent set correctly. That's a bit tricky to do if the parent is not a container control. Like a PictureBox. The designer will make the Form the parent so you will see the form's background, not the picture box. You'll need to fix that in code, edit the form constructor and make it look similar to this:
var pos = this.PointToScreen(userControl11.Location);
userControl11.Parent = pictureBox1;
userControl11.Location = pictureBox1.PointToClient(pos);
In constructor set style of control to support a transparent backcolor
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
and then set Background to transperent color
this.BackColor = Color.Transparent;
From MSDN
A more complex approach (and possibly working one) is described here - with overrding of CreateParams and OnPaint.
Why all those things?
UserControl class has property Region.
Set this to what ever shape you like and no other adjustments are needed.
public partial class TranspBackground : UserControl
{
public TranspBackground()
{
InitializeComponent();
}
GraphicsPath GrPath
{
get
{
GraphicsPath grPath = new GraphicsPath();
grPath.AddEllipse(this.ClientRectangle);
return grPath;
}
}
protected override void OnPaint(PaintEventArgs e)
{
// set the region property to the desired path like this
this.Region = new System.Drawing.Region(GrPath);
// other drawing goes here
e.Graphics.FillEllipse(new SolidBrush(ForeColor), ClientRectangle);
}
}
The result is as in the image below:
No low level code, no tweaking, simple and clean.
There is however one issue but in most cases it can go undetected, the edges are not smooth and anti-aliasing will not help either.
But the workaround is fairly easy. In fact much easier than all those complex background handling..

Movable Rectangle or Label

I am writing a program in Visual C# 2010 that has several icons on the form. When the mouse is placed over the icon (which is just an image) I want the icon to b highlighted via a border around the icon. In visual basic i can make a transparent rectangle with a colored border and position it over the icon. In C#, i can do the same however until i call invalidate multiple borders appear. The problem with calling invalidate is that my program is doing something in the background every second so the border keeps flashing (re-drawing).
Anyone got any ideas how i can implement this?
You didn’t say how you draw the border but from your description you are creating a graphics context for this. Don’t do this, it’s wrong. Instead, draw inside the Paint element of either the control or the its parent container.
The Paint event handler could look as follows:
private void yourControl_Paint(object sender, PaintEventArgs e)
{
if (! HasFocus(yourControl))
return;
Graphics g = e.Graphics;
using (Pen p = new Pen(Color.FromArgb(128, 0, 0, 128)))
g.DrawRectangle(p, 0, 0, yourControl.Width -1, yourControl.Height - 1);
}
This uses a hypothetical HasFocus method to determine whether this control should have a focus rectangle.
By the way, this is identical in VB and C#.

Simple rectangle box

How do put rectangular box around few controls on my winform? (i dont want the grouping thing).
If you don't want to use a GroupBox, you can put your controls in a Panel and set its BorderStyle property to BorderStyle.FixedSingle or BorderStyle.Fixed3D.
What's wrong with the GroupBox control? Grouping together a related set of controls is exactly what it's intended for. Your users have seen it in every other application they use, and throughout the Windows shell. They're much more likely to recognize what it means than your own custom-drawn rectangle. Deviating from standard platform conventions is rarely a good idea. I strongly recommend using the GroupBox control, even if it's not exactly the perfect look that you had in mind.
That being said, it's certainly possible to draw your own box around a group of controls on a form. To do so, you'll need to override your form's OnPaint method and write some code to draw a rectangle. Doing it this way gives you complete control over the color of your box, as well as the line thickness.
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
// Call the base class
base.OnPaint(e);
// Create your drawing pen
using (Pen p = new Pen(SystemColors.WindowText, 2.0))
{
// Calculate the position and dimensions of the box
Rectangle rect = new Rectangle(10, 10, 30, 30);
// Draw the rectangle
e.Graphics.DrawRectangle(p, rect);
}
}
The only thing you'll need to add is the code that calculates the dimensions of your rectangle, relative to the controls you want it to surround. Use the Location property of each control to get this information.
You can put your controls into a panel and set its BorderStyle from None to FixedSingle - it is the easiest way
http://msdn.microsoft.com/en-us/library/cyh3c8h8.aspx
Pen pen = new Pen(Color.FromArgb(255, 0, 0, 0));
e.Graphics.DrawLine(pen, 20, 10, 300, 100);
You can draw lines on a windows form this way. This would hook into the Paint method where e is PaintEventArgs

Why do my WinForms controls flicker and resize slowly?

I'm making a program where I have a lot of panels and panels in panels.
I have a few custom drawn controls in these panels.
The resize function of 1 panel contains code to adjust the size and position of all controls in that panel.
Now as soon as I resize the program, the resize of this panel gets actived. This results in a lot of flickering of the components in this panel.
All user drawn controls are double buffered.
Can some one help me solve this problem?
To get rid of the flicker while resizing the win form, suspend the layout while resizing. Override the forms resizebegin/resizeend methods as below.
protected override void OnResizeBegin(EventArgs e) {
SuspendLayout();
base.OnResizeBegin(e);
}
protected override void OnResizeEnd(EventArgs e) {
ResumeLayout();
base.OnResizeEnd(e);
}
This will leave the controls intact (as they where before resizing) and force a redraw when the resize operation is completed.
Looking at the project you posted, the flickering is really bad when you have the first tab selected, with the gradient-filled group boxes. With the second or third tab showing, there's hardly any flicker, if at all.
So clearly the problem has something to do with the controls you're showing on that tab page. A quick glance at the code for the custom gradient-filled group box class gives away the more specific cause. You're doing a lot of really expensive processing each time you draw one of the groupbox controls. Because each groupbox control has to repaint itself each time the form is resized, that code is getting executed an unbelievable number of times.
Plus, you have the controls' background set to "Transparent", which has to be faked in WinForms by asking the parent window to draw itself first inside the control window to produce the background pixels. The control then draws itself on top of that. This is also more work than filling the control's background with a solid color like SystemColors.Control, and it's causing you to see the form's pixels being drawn while you resize the form, before the groupboxes have a chance to paint themselves.
Here's the specific code I'm talking about from your custom gradient-filled groupbox control class:
protected override void OnPaint(PaintEventArgs e)
{
if (Visible)
{
Graphics gr = e.Graphics;
Rectangle clipRectangle = new Rectangle(new Point(0, 0), this.Size);
Size tSize = TextRenderer.MeasureText(Text, this.Font);
Rectangle r1 = new Rectangle(0, (tSize.Height / 2), Width - 2, Height - tSize.Height / 2 - 2);
Rectangle r2 = new Rectangle(0, 0, Width, Height);
Rectangle textRect = new Rectangle(6, 0, tSize.Width, tSize.Height);
GraphicsPath gp = new GraphicsPath();
gp.AddRectangle(r2);
gp.AddRectangle(r1);
gp.FillMode = FillMode.Alternate;
gr.FillRectangle(new SolidBrush(Parent.BackColor), clipRectangle);
LinearGradientBrush gradBrush;
gradBrush = new LinearGradientBrush(clipRectangle, SystemColors.GradientInactiveCaption, SystemColors.InactiveCaptionText, LinearGradientMode.BackwardDiagonal);
gr.FillPath(gradBrush, RoundedRectangle.Create(r1, 7));
Pen borderPen = new Pen(BorderColor);
gr.DrawPath(borderPen, RoundedRectangle.Create(r1, 7));
gr.FillRectangle(gradBrush, textRect);
gr.DrawRectangle(borderPen, textRect);
gr.DrawString(Text, base.Font, new SolidBrush(ForeColor), 6, 0);
}
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
if (this.BackColor == Color.Transparent)
base.OnPaintBackground(pevent);
}
And now that you've seen the code, red warning flags ought to go up. You're creating a bunch of GDI+ objects (brushes, pens, regions, etc.), but failing to Dispose any of them! Almost all of that code should be wrapped in using statements. That's just sloppy coding.
Doing all of that work costs something. When the computer is forced to devote so much time to rendering controls, other things lag behind. You see a flicker as it strains to keep up with the resize. It's no different than anything else that overloads a computer (like a computing the value of pi), it's just really easy to do so when you use as many custom drawn controls like you do here. Transparency is hard in Win32, and so is a lot of custom 3D painting. It makes the UI look and feel clunky to the user. Yet another reason that I don't understand the rush away from native controls.
You really only have three options:
Deal with the flicker. (I agree, this is not a good option.)
Use different controls, like the standard, built-in ones. Sure, they may not have a fancy gradient effect, but that's going to look broken half of the time anyway if the user has customized their Windows theme. It's also reasonably hard to read black text on a dark gray background.
Change the painting code within your custom controls to do less work. You may be able to get by with some simple "optimizations" that don't cost you any of the visual effects, but I suspect this is unlikely. It's a tradeoff between speed and eye candy. Doing nothing is always faster.
I successfully eliminate flicker when form resize using this code. Thanks.
VB.NET
Public Class Form1
Public Sub New()
Me.SetStyle(ControlStyles.UserPaint Or ControlStyles.OptimizedDoubleBuffer Or ControlStyles.AllPaintingInWmPaint Or ControlStyles.SupportsTransparentBackColor, True)
End Sub
Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
Me.Update()
End Sub
End Class
C#
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Resize += Form1_Resize;
this.SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true);
}
private void Form1_Resize(object sender, System.EventArgs e)
{
this.Update();
}
}
So I ran into this same problem - my control with a transparent background was repainting like 34 times, and what worked for me was:
On my form that contained the control
protected override void OnResize(EventArgs e)
{
myControl.Visible = false;
base.OnResize(e);
myControl.Visible = true;
}
And the same in the control:
protected override void OnResize(EventArgs e)
{
this.Visible = false;
base.OnResize(e);
this.Visible = true;
}
This reduced the amount of repainting to 4, which effectively eliminated any flicker when the control was being resized.
Maybe a good solution for you will be to use Form.ResizeBegin and Form.ResizeEnd events.
On ResizeBegin set main panel visibility to false, on ResizeEnd set main panel visibility to true.
This way panels will not be redrawn while someone is resizing your form.
While hooking into ResizeBegin and ResizeEnd is the right idea, instead of hiding the main panel's visibility I'd instead delay any resize calculations until ResizeEnd. In this case, you don't even need to hook into ResizeBegin or Resize - all the logic goes into ResizeEnd.
I say this for two reasons. One, even though the panel is hidden, the resize operation will likely still be expensive and so the form won't feel as responsive as it should unless the resize calculations are delayed. Two, hiding the pane's contents while resizing can be jarring to the user.
I had the same problem.
It seams that this is happening because you are using rounded corners. When I set CornerRadius property to 0, the flickering was gone.
So far I have only found the following workaround. Not the nicest one, but it stops the flickering.
private void Form_ResizeBegin(object sender, EventArgs e)
{
rectangleShape.CornerRadius = 0;
}
private void Form_ResizeEnd(object sender, EventArgs e)
{
rectangleShape.CornerRadius = 15;
}
I Had A Similar Issue Like This. My Entire Form Was Resizing Slowly And The Controls Painted Them In An Ugly Manner. So This Helped Me:
//I Added This To The Designer File, You Can Still Change The WindowState In Designer View If You Want. This Helped Me Though.
this.WindowState = FormWindowState.Maximized;
And In The Resize Event, Add This Code To The Beginning
this.Refresh();

Categories

Resources