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
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);
To create a panel with border I place a panel in a panel. The "border panel" has the background color of the wanted border color and a padding, while the padding size is the wanted border thickness.
The advantage of this solution is that there is no flickering and no problems with resize.
This can be very simple be created in the designer or in code behind.
Code behind:
Panel panel_Border = new Panel();
Panel panel_Embedded = new Panel();
panel_Border.BackColor = Color.Green;
panel_Border.Controls.Add(panel_Embedded);
// this is the border thickness
panel_Border.Padding = new System.Windows.Forms.Padding(6);
panel_Border.Size = new System.Drawing.Size(200, 100);
panel_Embedded.BackColor = System.Drawing.SystemColors.Control;
panel_Embedded.Dock = System.Windows.Forms.DockStyle.Fill;
Create a new, slightly larger panel and set the background colour to Black (or whatever). Place the original panel INSIDE the larger panel.
Related
I want to place a Label on top of a gif inside a PictureBox in winforms.
The problem ist that the label has a white background. I want it to be transparent.
My Code is as follows:
this.pictureBox = new PictureBox();
this.pictureBox.Image = Image.FromFile("my_background.gif");
this.pictureBox.Dock = DockStyle.Fill;
this.pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
this.label = new Label();
this.label.Text = "Hallo";
this.label.BackColor = Color.Transparent;
this.label.Location = new System.Drawing.Point(100, 100);
this.Controls.Add(this.label);
this.Controls.Add(this.pictureBox);
My problem is that the Label has a white Background even though the background is set to transparent. The solution for other having a similar problem was setting the parent of the label to the picture Box like this:
this.label.parent = this.pictureBox;
But that didn't solve the problem for me. Is there any other way to achieve this?
Thanks for any answers.
Thanks for the hint.
It worked fine when putting only a view controls in front of the gif. When adding to many it got very buggy and only some rectangular parts of the gif would update.
I solved the problem by splitting my gif into single images and displaying them in the OnPaint Event of the form
this.Paint += new PaintEventHandler(this.Paint_Background);
The Paint Method looked like this.
private void Paint_Background(object sender, PaintEventArgs e)
{
Graphics background_graphics = e.Graphics;
Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
int image_num = ((int)((DateTime.Now - start_time).TotalMilliseconds) / gif_speed) % num_images;
Image background= Image.FromFile("Filename_"+image_num+".jpg");
background_graphics.DrawImage(background, 0, 0, ClientSize.Width, ClientSize.Height);
background.Dispose();
}
All of my Controls where added directly to the view and not the imagebox anymore, as the imagebox was removed entirely.
Maybe this can help someone else too
I draw my contents on a form inside OnPaint event with e.graphics.DrawLine(), etc... . So far I was drawing according to form size (resizing my elements) but now I'd like draw as big as I want, and if I draw outside the visible area (the place where object will be drawn is decided at runtime dynamically), I want user to use scroll bars in order to see parts of whole content which I draw.
I have enabled AutoScrolling but I don't know how it may help me when I don't have any controls on that form.
How can I do it?
Simply set the AutoScrollMinSize property to the size you want. The scrollbar(s) automatically appear when the form's ClientSize is smaller than this value. You'll also need to offset what you draw according to the scroll position, like this:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.AutoScroll = true;
this.AutoScrollMinSize = new Size(3000, 1000);
this.ResizeRedraw = true;
}
protected override void OnPaint(PaintEventArgs e) {
e.Graphics.TranslateTransform(this.AutoScrollPosition.X, this.AutoScrollPosition.Y);
e.Graphics.DrawLine(Pens.Black, 0, 0, 3000, 1000);
base.OnPaint(e);
}
}
First you should set AutoScroll = true; of that Form where you're drawing ,than the best way is to draw things into a Panel and Re-size the Panel to fit the Content drawled inside ,than the Form will Automatically Show it's Scroll Bar's.
I am trying to implement a "Fillable Form" in which editable text fields appear over top of an image of a pre-preprinted form for a dot matrix printer. (using c# and Windows Forms and targeting .Net 2.0) My first idea was to use the image as the Windows Form background, but it looked horrible when scrolling and also did not scroll properly with the content.
My next attempt was to create a fixed-size window with a panel that overflows the bounds of the window (for scrolling purposes.) I added a PictureBox to the panel, and added my textboxes on top of it. This works fine, except that TextBoxes do not support transparency, so I tried several methods to make the TextBoxes transparent. One approach was to use an odd background color and a transparency key. Another, described in the following links, was to create a derived class that allows transparency:
Transparency for windows forms textbox
TextBox with a Transparent Background
Neither method works, because as I have come to find out, "transparency" in Windows Forms just means that the background of the window is painted onto the control background. Since the PictureBox is positioned between the Window background and the TextBox, it gives the appearance that the TextBox is not transparent, but simply has a background color equal to the background color of the Window. With the transparency key approach, the entire application becomes transparent so that you can see Visual Studio in the background, which is not what I want. So now I am trying to implement a class that derives from TextBox and overrides either OnPaint or OnPaintBackground to paint the appropriate part of the PictureBox image onto the control background to give the illusion of transparency as described in the following link:
How to create a transparent control which works when on top of other controls?
First of all, I can't get it working (I have tried various things, and either get a completely black control, or just a standard label background), and second of all, I get intermittent ArgumentExceptions from the DrawToBitmap method that have the cryptic message "Additional information: targetBounds." Based on the following link from MSDN, I believe that this is because the bitmap is too large - in either event it seems inefficient to capture the whole form image here because I really just want a tiny piece of it.
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.drawtobitmap(v=vs.100).aspx
Here is my latest attempt. Can somebody please help me with the OnPaintBackground implementation or suggest a different approach? Thanks in advance!
public partial class TransparentTextbox : TextBox
{
public TransparentTextbox()
{
InitializeComponent();
SetStyle(ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
//base.OnPaintBackground(e); // not sure whether I need this
if (Parent != null)
{
foreach (Control c in Parent.Controls)
{
if (c.GetType() == typeof(PictureBox))
{
PictureBox formImg = (PictureBox)c;
Bitmap bitmap = new Bitmap(formImg.Width, formImg.Height);
formImg.DrawToBitmap(bitmap, formImg.Bounds);
e.Graphics.DrawImage(bitmap, -Left, -Top);
break;
}
}
Debug.WriteLine(Name + " didn't find the PictureBox.");
}
}
}
NOTE: This has been tagged as a duplicate, but I referenced the "duplicate question" in my original post, and explained why it was not working. That solution only works if the TextBox sits directly over the Window - if another control (such as my Panel and PictureBox) sit between the window and the TextBox, then .Net draws the Window background onto the TextBox background, effectively making its background look gray, not transparent.
I think I have finally gotten to the bottom of this. I added a Bitmap variable to my class, and when I instantiate the textboxes, I am setting it to contain just the portion of the form image that sits behind the control. Then I overload OnPaintBackground to display the Bitmap, and I overload OnPaint to manually draw the text string. Here is the updated version of my TransparentTextbox class:
public partial class TransparentTextbox : TextBox
{
public Bitmap BgBitmap { get; set; }
public TransparentTextbox()
{
InitializeComponent();
SetStyle(ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawString(this.Text, this.Font, Brushes.Black, new PointF(0.0F, 0.0F));
}
protected override void OnPaintBackground(PaintEventArgs e)
{
e.Graphics.DrawImage(BgBitmap, 0, 0);
}
}
... and here is the relevant part of how I instantiate:
Bitmap bgImage = (Bitmap)Bitmap.FromStream(Document.FormImage);
PictureBox pb = new PictureBox();
pb.Image = bgImage;
pb.Size = pb.Image.Size;
pb.Top = 0;
pb.Left = 0;
panel1.Controls.Add(pb);
foreach (FormField field in Document.FormFields)
{
TransparentTextbox tb = new TransparentTextbox();
tb.Width = (int)Math.Ceiling(field.MaxLineWidth * 96.0);
tb.Height = 22;
tb.Font = new Font("Courier", 12);
tb.BorderStyle = BorderStyle.None;
tb.Text = "Super Neat!";
tb.TextChanged += tb_TextChanged;
tb.Left = (int)Math.Ceiling(field.XValue * 96.0);
tb.Top = (int)Math.Ceiling(field.YValue * 96.0);
tb.Visible = true;
Bitmap b = new Bitmap(tb.Width, tb.Height);
using (Graphics g = Graphics.FromImage(b))
{
g.DrawImage(bgImage, new Rectangle(0, 0, b.Width, b.Height), tb.Bounds, GraphicsUnit.Pixel);
tb.BgBitmap = b;
}
panel1.Controls.Add(tb);
}
I still need to work on how the text looks when I highlight it, and other things like that, but I feel like I am on the right track. +1 to Reza Aghaei and Mangist for commenting with other viable solutions!
I want to add Buttons to a FlowLayoutPanel. The Buttons might contain longer texts with spaces between the words. The Buttons are Autosize=true and AutoSizeMode = AutoSizeMode.GrowAndShrink. Further more I set the MaximumSize property to (maxwidth,0). maxwidth is the width of the panel. So the button does not grow too wide.
What I see is, that the widht of the Button is limited by the MaximumSize property, but when text wrapping occurs, the Button's height doesn't autosize to the height of the wrapped text. Is there a solution to that problem?
I also tried this manually sizing the button like this:
using (Graphics cg = this.CreateGraphics()) {
SizeF size = cg.MeasureString(button.Text, button.Font, 200);
button.Width = (int)size.Width+20;
button.Height = (int)size.Height+20;
button.Text = someLongTextWithSpaces;
}
But please note that I added 20 to the calculated size. It's working, but is there a proper way to determin this additional size? Maybe 2x Padding + ?????
A few hours later...
I came to this version which seems to work quite fine.
using (Graphics cg = this.CreateGraphics()) {
var fmt = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;
var prop = new Size(tableLayoutPanel1.Width - 20, 0);
var size = TextRenderer.MeasureText(button.Text, button.Font, prop, fmt);
int border = button.Height - button.Font.Height;
button.Width = (int)size.Width + border;
button.Height = (int)size.Height + border;
button.Text = someLongTextWithSpaces;
}
It seems that the initial button height is borders + the height the font. So I calculated the border subtracting button.Height-button.font.Height.
According to Hans, I now use the TextRenderer.MeasureText. I tested it without enabling VisualStyles and it worked fine. Any comments on that?
There is a proper way, but it isn't exactly very subtle. Reverse-engineering it from the ButtonRenderer class source code, the Winforms class that draws the button text, you must use the TextRenderer class to measure the text. And you must use the VisualStyleRenderer.GetBackgroundContentRectangle() method to obtain the effective drawing bounds. Note that it is smaller than the button's Size because of the border and a margin that depends on the selected visual style.
Non-trivial problems are mapping a calculated content rectangle back to the outer button size and dealing with old machines that don't have visual styles enabled. Sample code that appeared to arrive at the correct size:
private static void SetButtonSize(Graphics gr, Button button) {
VisualStyleElement ButtonElement = VisualStyleElement.Button.PushButton.Normal;
var visualStyleRenderer = new VisualStyleRenderer(ButtonElement.ClassName, ButtonElement.Part, 0);
var bounds = visualStyleRenderer.GetBackgroundContentRectangle(gr, button.Bounds);
var margin = button.Height - bounds.Height;
var fmt = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;
var prop = new Size(bounds.Width, 0);
var size = TextRenderer.MeasureText(button.Text, button.Font, prop, fmt);
button.ClientSize = new Size(button.ClientSize.Width, size.Height - margin);
}
protected override void OnLoad(EventArgs e) {
using (var gr = this.CreateGraphics()) {
SetButtonSize(gr, this.button1);
}
base.OnLoad(e);
}
Not extensively tested for corner cases, can't say I recommend this.
It seems that the initial button height is borders + the height the font. So I calculated the border subtracting button.Height-button.font.Height. (See the last block of my original post)
This also works with VisualStyles enabled/disabled.
You should control the line breaks by adding newline characters in the text. Automatic text wrapping won't work with spaces alone:
button1.Text = "123232131232\r\nfgfdgfdgdfgdfgdf\r\nASDSADSDASD";
Or :
button1.Text = "123232131232" + Environment.NewLine +
"fgfdgfdgdfgdfgdf" + Environment.NewLine + "ASDSADSDASD";
If you'd rather get the automatic wrapping you could try to use TextMeasure to determine the height needed for the text and then set the button's height accordingly but that may need some extra attention..
But I suggest to consider using Labels instead. For a Label the wrapping works out of the box.. Huge Buttons with varying sizes are non-standard UI elements.
How do I resize button backgroundImage in c#?
I could only find properties which gets button backgroundImage size.
Nothing sets size.
I use WinForms
BackgroundImageLayout would help...If Not then,
1)Take a Panel (panel1).
2)Bind you Button Event to panel(panel1)
3)Add another panel (panel2) to Panel1 in above with background image that you want to set and BackgroundImageLayout property as ImageLayout.Stretch
4)Then Resize the panel2
this would resize your image
Hope this helps
I will not get any simpler than that in WinForms:
private void yourbutton_Paint(object sender, PaintEventArgs e)
{
// base.OnPaint(e); optional
Rectangle rc = yourButton.ClientRectangle;
Rectangle ri = new Rectangle(Point.Empty, yourButton.BackgroundImage.Size);
// e.Graphics.FillRectangle(SystemBrushes.Control, rc); optional
e.Graphics.DrawImage(yourButton.BackgroundImage, rc, ri, GraphicsUnit.Pixel);
e.Graphics.DrawString(yourButton.Text, yourButton.Font,
SystemBrushes.ControlText, Point.Empty); // if needed
}
If you look at the code you'll see that it effectively really is just one line, or two if you have text on the button..