Draw a rectangle - c#

For some reason the rectangle doesn't show up when I run the program. But the code runs without any errors. What am I doing wrong?
(I am using csc.exe to compile the code, and I'm writing it in notepad++)
Drawing code:
Graphics g = myform.CreateGraphics();
Pen selPen = new Pen(Color.Blue);
g.DrawRectangle(selPen, 10, 10, 50, 50);
g.Dispose();
Complete Code:
using System;
using System.Windows.Forms;
using System.Drawing;
public class Hello1
{
public static void Main()
{
Form myform = new Form();
myform.Text = "Main Window";
myform.Size = new Size(640, 400);
myform.FormBorderStyle = FormBorderStyle.FixedDialog;
myform.StartPosition = FormStartPosition.CenterScreen;
Graphics g = myform.CreateGraphics();
Pen selPen = new Pen(Color.Blue);
g.DrawRectangle(selPen, 10, 10, 50, 50);
g.Dispose();
myform.ShowDialog();
}
}

You can draw on a form in the Form.OnPaint method override or in the Form.Paint event handler only.
So you need to create a new class inherited from Form:
public class MyForm : Form
{
}
Add the following code to your form:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
using (Pen selPen = new Pen(Color.Blue))
{
g.DrawRectangle(selPen, 10, 10, 50, 50);
}
}
Alternatively, you could subscribe to the myform.Paint event as follows:
myform.Paint += (o, e) => {
Graphics g = e.Graphics;
using (Pen selPen = new Pen(Color.Blue))
{
g.DrawRectangle(selPen, 10, 10, 50, 50);
}
};

This is because the form is painted when it is shown (in your case when ShowDialog is called), and that erases the rectangle you drew.
You have to draw the rectangle:
After the form is shown. For instance, in the Shown event of the form - but beware that when the form will be painted again, the rectangle will disappear (for instance when you minimize/maximize the form),
Or better, while the form is painted (in the Paint event, see Dmitry's answer).

If you rearrange the code to put the drawing code after the showing part, you can see the rectangle. As no lines are read after ShowDialog() until the shown form is closed, you might need to call the Show() method.
public static void Main()
{
Form myform = new Form();
myform.Text = "Main Window";
myform.Size = new Size(640, 400);
myform.FormBorderStyle = FormBorderStyle.FixedDialog;
myform.StartPosition = FormStartPosition.CenterScreen;
myform.Show(); // -> First Show
// -> Then Draw
Graphics g = myform.CreateGraphics();
Pen selPen = new Pen(Color.Blue);
g.DrawRectangle(selPen, 10, 10, 50, 50);
g.Dispose();
}
By doing so, you can see the rectangle. But it will not remain there unless you add the drawing part on its OnPaint event Handler. The drawn rectangle will be vanished when you try to minimize or move the side containing the rectangle, or wheneever the form needs to be Drawn by the OS.

Related

How to dark background when my form opens?

I am writing the app, and a part of it is open textbox. When the textbox is opening I want to dark background.
I have looked the solution and found it here:
Creating a dark background when a new form appears
But, it does not work for me correctly.
Here is my code:
private void App_Load(object sender, EventArgs e)
{
this.Text = "TestApp";
this.Size = new Size(350, 250);
this.BackColor = Color.DarkGray;
this.Location = new Point(50, 50);
this.MaximizeBox = false;
TextBox.BackColor = Color.WhiteSmoke;
TextBox.Multiline = true;
TextBox.Size = new Size(200, 90);
Button.Text = "Search";
Bitmap bmp = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);
using (Graphics G = Graphics.FromImage(bmp))
{
G.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
G.CopyFromScreen(this.PointToScreen(new Point(0, 0)), new Point(0, 0), this.ClientRectangle.Size);
double percent = 0.60;
Color darken = Color.FromArgb((int)(255 * percent), Color.Black);
using (Brush brsh = new SolidBrush(darken))
{
G.FillRectangle(brsh, this.ClientRectangle);
}
}
using (Panel p = new Panel())
{
p.Location = new Point(0, 0);
p.Size = this.ClientRectangle.Size;
p.BackgroundImage = bmp;
this.Controls.Add(p);
p.BringToFront();
// display your dialog somehow:
Form frm = new Form();
frm.StartPosition = FormStartPosition.Manual;
frm.ShowDialog(this);
}
}
I receive this:
Maybe, someone can point me out where is my mistake?
EDIT: I have found the solution, the question was not clear enough.
When the textbox is opening I want to dark background.
So you want the textBox to be dark, not the complete form?
Almost always when you think you have to do some painting yourself, think again. It is seldom necessary do to paint. Only do this, if you don't have any standard options.
Just set Property BackGround of the text box. Use visual studio designer to do this.
If you don't want to do this using the designer, do this in the constructor after InitializeComponent:
public MyForm()
{
InitializeComponent();
// text box dark background:
this.textBox1.BackColor = Color.Black;
}
If you want the complete form to be black, again use visual studio designer, or add:
InitializeComponent();
this.BackColor = Color.Black;

c# - Dynamically creating picture box from dll into a form

I'm trying to dynamically create a picture box by clicking a button. However, I want to have the code that creates the picture box (and also creates some graphs in that picture box) in a dll file. When i move the code from my main form to a method in a dll file and then call that method in the button click event in my main form nothig happens.
I've been searching high and low for an answer but with little success. The most relevant thing that I found is here. However, I struggle to create an instance of my main form to pass to the method in the dll...The answer might be bluntly obvious but I am very new to c#... Also, I am using Visual Studio 2013 if that is of any relevance.
Here is the method in the dll:
namespace DrillGraph
{
public class DrillGraph : UserControl
{
public DrillGraph() { }
public void CreateGraph()
{
PictureBox pb = new PictureBox();
pb.Dock = DockStyle.Fill;
pb.BackColor = Color.Bisque;
pb.Name = "pb";
pb.Size = new Size(50, 50);
pb.Location = new Point(20, 20);
Graphics g = pb.CreateGraphics();
g.DrawEllipse(new Pen(Color.Red), 0, 0, 50, 50);
this.Controls.Add(pb);
}
}
}
And this is what i have in my main form:
using DrillGraph;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
DrillGraph.DrillGraph dg = new DrillGraph.DrillGraph();
private void button1_Click(object sender, EventArgs e)
{
dg.CreateGraph();
}
}
}
Adding where? you should provide the reference in your dll.
public void CreateGraph(Panel pnl)
{
PictureBox pb = new PictureBox();
pb.Dock = DockStyle.Fill;
pb.BackColor = Color.Bisque;
pb.Name = "pb";
pb.Size = new Size(50, 50);
pb.Location = new Point(20, 20);
Graphics g = pb.CreateGraphics();
g.DrawEllipse(new Pen(Color.Red), 0, 0, 50, 50);
pnl.Controls.Add(pb);
}
Then call below code
dg.CreateGraph(YourPanelName From Form);

Draw a rectangle in a panel of a form when a button click event is fired from another form

I'm currently working on windows form application where I have two forms; form1 and form2. There is a button inside form1 which opens form2 when clicked and what I want is to create a rectangle inside a panel of form1 when a button inside Form2 is clicked. I put some code to create rectangle inside the button click event of form2, but it showed nothing when clicked. However, whenever I put the draw.rectangle method inside the same form where button is clicked, it work, but differently it doesn't
Here's the code inside form1
private void btnSave_Click(object sender, EventArgs e)
{
Layoutsetting a = new Layoutsetting();
a.ShowDialog();
}
public void DrawObject()
{
Graphics g = panel1.CreateGraphics();
Rectangle rect = new Rectangle(10, 10, 80, 90);
rect.Inflate(-10, -10);
g.DrawRectangle(black, rect);
g.FillRectangle(Brushes.BlueViolet, rect);
StringFormat f = new StringFormat();
f.LineAlignment = StringAlignment.Center;
f.Alignment = StringAlignment.Center;
g.DrawString("Hello", this.Font, Brushes.GhostWhite, rect, f);
panel1.Refresh();
}
This is the code inside form2
private void btnConfirm_Click(object sender, EventArgs e)
{
Form1.Default.DrawObject();
this.Close();
}
The problem is not with drawing rectangle, the panel paint event fires whenever even a slightest part of the panel were hidden (for example a part of it was behind another form) and redraws the panel, so the rectangle disappears (but when it is the active form which paint event doesn't fire, the rectangle will be drawn and will not be cleared unless you do something that panel needs to be redrawn.).
Easy Solution:
Create an image of recangle and use it as background image when needed, instead of drawing it.
Another Solution:
add a property to your form (or your panel):
public bool NeedsToBeDrawn {get; set;}
instead of this line of code:
Form1.Default.DrawObject();
just set the property to true:
Form1.NeedsToBeDrawn = true;
and move your code to your panel's paint event:
private void panel1_Paint(object sender, PaintEventArgs e)
{
if(NeedsToBeDrawn)
{
Rectangle rect = new Rectangle(10, 10, 80, 90);
rect.Inflate(-10, -10);
e.Graphics.DrawRectangle(black, rect);
e.Graphics.FillRectangle(Brushes.BlueViolet, rect);
StringFormat f = new StringFormat();
f.LineAlignment = StringAlignment.Center;
f.Alignment = StringAlignment.Center;
e.Graphics.DrawString("Hello", this.Font, Brushes.GhostWhite, rect, f);
}
}
You have to add a method to Paint:
panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.draw);
private void draw(object sender, PaintEventArgs e)
{
if(buttonClicked) {
Graphics g = e.Graphics;
//...
}
}

GDI :Figure out which color the pixel has, which I drew before

I am trying to figure out which color the Pixel has which I drew before in red.
So as I read its not possible to do that directly, transformed my Graphics object to a Bitmap, which has the function GetPIxel and same width/height as my graphics object. Otherwise i think it would not function.
But it always returns me: Color [A=0, R=0, G=0, B=0]
Which i guess means White.
Here is my Code:
namespace GDi
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.components = new System.ComponentModel.Container();
this.Size = new System.Drawing.Size(400, 400);
this.Text = "Display At Startup";
this.BackColor = Color.White;
}
private void Form1_Load(object sender, EventArgs e)
{
Graphics dc = this.CreateGraphics();
this.Show();
Pen BluePen = new Pen(Color.Blue, 3);
dc.DrawRectangle(BluePen, 0, 0, 50, 50);
Pen RedPen = new Pen(Color.Red, 2);
dc.DrawEllipse(RedPen, 20, 70, 80, 0);
dc.DrawEllipse(RedPen, 2, 88, 300, 0);
Bitmap myBitmap = new Bitmap(400, 400, dc);
string test = myBitmap.GetPixel(2, 88).ToString();
MessageBox.Show(test);
}
}
}
Any idea why it doesent works?
It doesn't work because the Bitmap constructor simply creates a new empty bitmap with no relation to your previous drawing.
You should probably use a different approach:
Create a Bitmap object like you've done
Create a Graphics object to draw in this bitmap using Graphics.FromImage method
Draw into this new Graphics
When needed, read the pixel color you need from your bitmap
When the drawing is done, copy the bitmap to the form
Dispose your new Graphics and Bitmap objects. Alternatively, you may hold the Bitmap for a long time, but Graphics should better be created on each redraw.

How to draw an ellipse C# via GDI?

I am new in C# and i am trying to draw a color filled ellipse, I foud some code but i couldn't figure out how to do it.
I tried with this code:
Graphics g = this.CreateGraphics();
Pen pen = new Pen(Color.Aquamarine, 2);
g.DrawEllipse(pen, 10, 10, 100, 20);
But the method does not exist.
Colud you help me?
Thanks in advance.
You should do your graphics drawing in the forms Paint Event, otherwise as soon as the screen updates you will loose your drawing. This is a quick and dirty example on how to do so.
public Form1()
{
InitializeComponent();
this.Paint += new PaintEventHandler(Form1_Paint);
}
void Form1_Paint(object sender, PaintEventArgs e)
{
Pen pen = new Pen(Color.Aquamarine,2);
SolidBrush brush = new SolidBrush(Color.Aquamarine);
e.Graphics.DrawEllipse(pen, 10, 10, 100, 20);
e.Graphics.FillEllipse(brush, 10, 50, 100, 20);
}

Categories

Resources