Printing out Panel in C# - c#

Again, I am asking a question about a USB Printer. This time however, the issue is more on the programming end of the spectrum.
I have a windows forms application in which I generate a receipt, which is then supposed to be sent to the printer. The Following things work: Generating the receipt, Sending the data to the printer.
The data however is only an empty strip of paper. I have the feeling that the Software is ignoring the Panel contents and just sends the empty panel to the printer.
The Sourcecode is as follows:
namespace MakeyMakey
{
public partial class Form1 : Form
{
public void Gridsettings()
{
GVReceipt.ScrollBars = ScrollBars.None;
GVReceipt.RowHeadersVisible = false;
GVReceipt.ColumnCount = 3;
GVReceipt.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
GVReceipt.CellBorderStyle = DataGridViewCellBorderStyle.None;
}
public Form1()
{
InitializeComponent();
pCompanyImage.SizeMode = PictureBoxSizeMode.StretchImage;
Bitmap Logo = new Bitmap(Bitmap.FromFile(#"C:/Users/manue/source/repos/MakeyMakey/MakeyMakey/logo.png"));
pCompanyImage.Image = MakeBW(Logo);
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode("Hier kann so gut wie alles stehen", QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
Bitmap qrCodeImage = qrCode.GetGraphic(20);
pQRCode.Image = qrCodeImage;
panel1.Height = GVProduct.Height + 220;
GVReceipt.Columns.Add("Name", "Name");
GVReceipt.Columns.Add("QTY", "QTY");
GVReceipt.Columns.Add("Price", "Price");
GVReceipt.Columns[0].Width = 50;
GVReceipt.Columns[1].Width = 15;
GVReceipt.Columns[2].Width = 50;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string[] row = new string[] {txtName.Text, txtQty.Text, txtPrice.Text };
GVReceipt.Rows.Add(row);
GVProduct.Rows.Add(row);
Gridsettings();
Calc();
txtName.Clear();
txtQty.Clear();
txtPrice.Clear();
txtName.Focus();
}
private void GVResize()
{
//MessageBox.Show(GVReceipt.Height.ToString());
GVReceipt.Height = GVReceipt.ColumnHeadersHeight + GVReceipt.RowCount * GVReceipt.Rows[0].Height;
//MessageBox.Show(GVReceipt.Height.ToString());
panel1.Height += GVReceipt.Rows[0].Height;
//MessageBox.Show(panel1.Height.ToString());
GVReceipt.ClearSelection();
Refresh();
}
private void GVReceipt_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
}
private void GVReceipt_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
panel1.Height = 389;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
public Bitmap MakeBW(Bitmap Map)
{
Bitmap newbmp = new Bitmap(Map.Width, Map.Height); // New image
for (int row = 0; row < Map.Width; row++) // Indicates row number
{
for (int column = 0; column < Map.Height; column++) // Indicate column number
{
var colorValue = Map.GetPixel(row, column); // Get the color pixel
var averageValue = ((int)colorValue.R + (int)colorValue.B + (int)colorValue.G) / 3; // get the average for black and white
newbmp.SetPixel(row, column, Color.FromArgb(averageValue, averageValue, averageValue)); // Set the value to new pixel
}
}
return newbmp;
}
public void Calc()
{
decimal total = 0;
for(int i = 0; i < GVReceipt.RowCount-1; i++)
{
total += Convert.ToDecimal(GVReceipt.Rows[i].Cells[2].Value) * Convert.ToDecimal(GVReceipt.Rows[i].Cells[1].Value);
}
//Console.WriteLine("HELLO");
//MessageBox.Show(total.ToString());
lbltotal.Text = total.ToString() + "€";
Refresh();
GVResize();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Print(panel1);
}
Bitmap MemoryImage;
PrintDocument printdoc1 = new PrintDocument();
PrintPreviewDialog previewdlg = new PrintPreviewDialog();
public void GetPrintArea(Panel pnl)
{
MemoryImage = new Bitmap(pnl.Width, pnl.Height);
Rectangle rect = new Rectangle(0, 0, pnl.Width, pnl.Height);
pnl.DrawToBitmap(MemoryImage, new Rectangle(0, 0, pnl.Width, pnl.Height));
}
public void printdoc1_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawImage(MemoryImage, 0, 0);
}
public void Print(Panel pnl)
{
GetPrintArea(pnl);
printdoc1.PrinterSettings.PrinterName = "Generico";
printdoc1.DefaultPageSettings.PaperSize = new PaperSize("Custom", panel1.Width, panel1.Height);
previewdlg.Document = printdoc1;
previewdlg.ShowDialog();
printdoc1.Print();
}
private void btnPrinter_Click(object sender, EventArgs e)
{
printDocument1.Print();
GVProduct.Rows.Clear();
GVReceipt.Rows.Clear();
Calc();
}
private void GVReceipt_RowsAdded_1(object sender, DataGridViewRowsAddedEventArgs e)
{
//GVResize();
}
}
I have also included two images, one shows what the receipt looks like, the other what the print preview generated.
I'd highy appreciate any help on that topic.

Related

Draw cross on a picture box and get center coordinates EMGU c#

I learn and now I am in a dilemma, silly, but for the newbie a dilemma, I have not been able to draw a line in the shape of a cross in my video window and that allows me to know the coordinates of the center of that cross.
I show you the current window
enter image description here
and then how I want it to look
enter image description here
I have searched in forums, youtube and more, but I can't find a simple example that will help me
It is an idea of ​​what I need, thank you very much for your help and patience
this is my code. They will notice how inexperienced I am
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
namespace Farmer_v._0._1._0
{
public partial class Vision_artificial : Form
{
//COLOR PICKER
[DllImport("user32.dll")]
static extern bool GetCursorPos(ref Point lpPoint);
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern int BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);
//COLOR PICKER
Emgu.CV.Capture capWebcam = null;
bool blnCapturingInProcess = false;
Image<Bgr, Byte> imgOriginal;
Image<Gray, Byte> imgProcesada;
Mat frame = new Mat();
//canny
double umbral11 = 300;
double umbral22= 300;
//circulos
double min_distancia = 4;
double umbralCirculos1 = 1;
double umbralCirculos2 = 1;
int min_diametro = 10;
int max_diametro = 400;
int n_circulos = 0;
//BGR
int B1 = 0;
int G1 = 0;
int R1 = 175;
int B2 = 100;
int G2 = 100;
int R2 = 256;
public Vision_artificial()
{
InitializeComponent();
}
public Color GetColorAt(Point location)
{
using (Bitmap screenPixel = new Bitmap(1, 1, PixelFormat.Format32bppRgb))
{
using (Graphics gdest = Graphics.FromImage(screenPixel))
{
using (Graphics gsrc = Graphics.FromHwnd(ibOriginal.Handle))
{
IntPtr hSrcDC = gsrc.GetHdc();
IntPtr hDC = gdest.GetHdc();
int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, location.X, location.Y, (int)CopyPixelOperation.SourceCopy);
gdest.ReleaseHdc();
gsrc.ReleaseHdc();
}
}
return screenPixel.GetPixel(0, 0);
}
}
public void Draw(Cross2DF cross, IColor color, int thickness)
{
}
private void Vision_artificial_Load(object sender, EventArgs e)
{
try
{
capWebcam = new Emgu.CV.Capture(1); //asociar captura de objeto a la camara por defecto
}
catch (NullReferenceException except) //si hay error
{
txtXYRadius.Text = except.Message; //muestra error de objeto en el cuadro de texto
return;
}
Application.Idle += processFrameAndUpdateGUI;
blnCapturingInProcess = true;
//camara.ImageGrabbed += Grabar;
//camara.Start();
}
private void Vision_artificial_Closed(object sender, EventArgs e)
{
if (capWebcam != null)
{
capWebcam.Dispose();
}
}
void processFrameAndUpdateGUI(object sender, EventArgs e)
{
imgOriginal = capWebcam.QueryFrame().ToImage<Bgr, Byte>();
if (imgOriginal == null) return;
imgProcesada = imgOriginal.InRange(new Bgr(B1, G1, R1),
new Bgr(B2, G2, R2));
imgProcesada = imgProcesada.SmoothGaussian(9);
CircleF[] circles = imgProcesada.HoughCircles(new Gray(100),
new Gray(50),
2,
imgProcesada.Height / min_distancia,
min_diametro,
max_diametro)[0];
foreach (CircleF circle in circles)
{
if (txtXYRadius.Text != "") txtXYRadius.AppendText(Environment.NewLine);
txtXYRadius.AppendText("Objeto en posicion x=" + circle.Center.X.ToString().PadLeft(4) +
", y =" + circle.Center.Y.ToString().PadLeft(4) +
", radius =" + circle.Radius.ToString("###.000").PadLeft(7));
txtXYRadius.ScrollToCaret();
n_circulos = circles.Length;
geoX.Text = circle.Center.X.ToString();
geoY.Text = circle.Center.Y.ToString();
CvInvoke.Circle(imgOriginal,
new Point((int)circle.Center.X, (int)circle.Center.Y),
3,
new MCvScalar(0, 255, 0),
-1,
Emgu.CV.CvEnum.LineType.FourConnected,
0);
imgOriginal.Draw(circle,
new Bgr(Color.Red),
3);
}
//Mat imagen2 = new Mat();
//CvInvoke.Canny(imgOriginal.Clone(), imagen2, umbral11, umbral22);
//ibCanny.Image = imagen2.Bitmap;
////circles = CvInvoke.HoughCircles(imagen2, HoughType.Gradient, 1.0, min_distancia, umbralCirculos1, umbralCirculos2, min_diametro, max_diametro);
//
//for (int i = 0; i < circles.Length; i++)
//{
// CvInvoke.Circle(imagen2,
// Point.Round(circles[i].Center), (int)circles[i].Radius, new Bgr(Color.Red).MCvScalar, 2, LineType.EightConnected, 0);
//}
ibOriginal.Image = imgOriginal.ToBitmap();
ibProcesada.Image = imgProcesada.ToBitmap();
}
//private void Grabar (object sender, EventArgs e)
//{
// Mat imagen = new Mat();
// camara.Retrieve(imagen, 0);
// ibOriginal.Image = imagen.Bitmap;
// Mat imagen2 = new Mat();
// CvInvoke.Canny(imagen.Clone(), imagen2, umbral11, umbral22);
// ibProcesada.Image = imagen2.Bitmap;
// CircleF[] circulos = CvInvoke.HoughCircles(imagen2.Clone(), HoughType.Gradient, 1.0, min_distancia, umbralCirculos1, umbralCirculos2, min_diametro, max_diametro);
// n_circulos = circulos.Length;
// Mat imagen3 =imagen.Clone();
// for (int i = 0; i < circulos.Length; i++)
// {
// CvInvoke.Circle(imagen3,
// Point.Round(circulos[i].Center), (int)circulos[i].Radius, new Bgr(Color.Red).MCvScalar, 2, LineType.EightConnected, 0);
// }
// ibCanny.Image = imagen3.Bitmap;
//}
private void Arduino(object sender, EventArgs e)
{
}
public Bitmap CannyEdge(Bitmap bmp)
{
Image<Gray, Byte> Cannybmp;
Image<Gray, Byte> GrayBmp;
Image<Bgr, Byte> orig = new Image<Bgr, Byte>(bmp);
Image<Bgr, Byte> imgSmooth;
Bitmap output;
imgSmooth = orig.PyrUp();
imgSmooth._SmoothGaussian(3);
GrayBmp = imgSmooth.Convert<Gray, byte>();
Gray grayCannyThreshold = new Gray(umbral11);
Gray grayThreshLinking = new Gray(umbral22);
Cannybmp = GrayBmp.Canny(grayCannyThreshold.Intensity, grayThreshLinking.Intensity);
output = Cannybmp.ToBitmap();
//int a = 5;
return output;
}
private void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
}
private void pictureBox2_Click(object sender, EventArgs e)
{
}
private void btnPausa_Click(object sender, EventArgs e)
{
if (blnCapturingInProcess == true)
{
Application.Idle -= processFrameAndUpdateGUI;
blnCapturingInProcess = false;
btnPausa.Text = "Capturar";
}
else
{
Application.Idle += processFrameAndUpdateGUI;
blnCapturingInProcess = true;
btnPausa.Text = "Pausa";
}
}
private void ibCanny_Click(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
umbral11 = (double)numericUpDown1.Value;
}
private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
umbral22 = (double)numericUpDown2.Value;
}
private void timer1_Tick(object sender, EventArgs e)
{
lbln_circulos.Text = n_circulos.ToString();
}
private void numericUpDown5_ValueChanged(object sender, EventArgs e)
{
umbralCirculos1 = (double)num_umbral_1.Value;
}
private void num_distanicia_minima_ValueChanged(object sender, EventArgs e)
{
min_distancia = (double)num_distancia_minima.Value;
}
private void num_umbral_2_ValueChanged(object sender, EventArgs e)
{
umbralCirculos2 = (double)num_umbral_2.Value;
}
private void num_diametro_minimo_ValueChanged(object sender, EventArgs e)
{
min_diametro = (int)num_diametro_minimo.Value;
}
private void num_diametro_maximo_ValueChanged(object sender, EventArgs e)
{
max_diametro = (int)num_diametro_maximo.Value;
}
private void boxB1_ValueChanged(object sender, EventArgs e)
{
B1 = (int)boxB1.Value;
}
private void boxG1_ValueChanged(object sender, EventArgs e)
{
G1 = (int)boxG1.Value;
}
private void boxR1_ValueChanged(object sender, EventArgs e)
{
R1 = (int)boxG1.Value;
}
private void boxB2_ValueChanged(object sender, EventArgs e)
{
B2 = (int)boxB2.Value;
}
private void boxG2_ValueChanged(object sender, EventArgs e)
{
G2 = (int)boxG2.Value;
}
private void boxR2_ValueChanged(object sender, EventArgs e)
{
R2 = (int)boxR2.Value;
}
private void button1_Click(object sender, EventArgs e)
{
}
private void ibOriginal_MouseDown(object sender, MouseEventArgs e)
{
}
private void ibOriginal_MouseMove(object sender, MouseEventArgs e)
{
panelColor.BackColor = GetColorAt(e.Location);
//Bitmap pixelData = new Bitmap (ibOriginal.Image);
//Color clr = pixelData.GetPixel(Cursor.Position.X - this.Left, Cursor.Position.Y - (this.Top +15));
//lblB.Text = "RGBA(" + clr.R.ToString() + ", " + clr.G.ToString() + ", " + clr.B.ToString();
}
}
}

How to change properties just one button

Hey,
I have multiple buttons.I want to reduce the code so that I can set the properties of a button, but only the one I click on will change.So that I don't click on button_1 and change all the others
public static void SetProp()
{
for (int i = 0; i < buttons.Count; i++)
{
buttons[i].Image = Properties.Resources.test;
buttons[i].Width = buttons[i].Image.Width;
buttons[i].Height = buttons[i].Image.Height;
buttons[i].ImageAlign = ContentAlignment.MiddleCenter;
buttons[i].Text = null;
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(0, 0, buttons[i].Width, buttons[i].Height);
buttons[i].Region = new Region(gp);
gp.Dispose();
}
}
private void button1_Click(object sender, EventArgs e)
{
SetProp();
}
public static void SetProp(Button button)
{
for (int i = 0; i < buttons.Count; i++)
{
button.Image = Properties.Resources.test;
button.Width = buttons[i].Image.Width;
button.Height = buttons[i].Image.Height;
button.ImageAlign = ContentAlignment.MiddleCenter;
button.Text = null;
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(0, 0, button.Width, button.Height);
button.Region = new Region(gp);
gp.Dispose();
}
}
private void button1_Click(object sender, EventArgs e)
{
SetProp(sender as Button);
}

Collision detection with duplicated picturebox

For my school I have to do a little project.
The aim of the project is to do a game which spawns different rectangles and you have to click them.
If you click them you recive points and the rectangle gets replaced with a new one.
And every timer tick the box gets bigger.
We have to use pictureboxes.
Now my question is:
How can I make a detection to indicate a picturebox which colides with the panel-border or with a other picture box.
The problem is, that the picboxes are getting duplicated.
So how can I solve this problem?
This is my code:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BoxClicker
{
public partial class Form1 : Form
{
private Random rndColor = new Random();
private Random rndCreation = new Random();
public Form1()
{
InitializeComponent();
}
private void CreateBox()
{
PictureBox gamebox = new PictureBox();
gamebox.Size = new Size(20, 20);
gamebox.Location = new Point(rndCreation.Next(0, pnlSpiel.Width - 30), rndCreation.Next(0, pnlSpiel.Height - 30));
gamebox.BackColor = Color.FromArgb(rndCreation.Next(0, 255), rndCreation.Next(0, 255), rndCreation.Next(0, 255));
pnlSpiel.Controls.Add(gamebox);
gamebox.Click += pictureBox1_Click;
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < numValues.Value; i++)
{
CreateBox();
}
tmrResize.Start();
txtNotification.Text = "Klicke auf die erscheinenden Boxen um Punkte zu sammeln!";
btnStart.Visible = false;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
CreateBox();
PictureBox gamebox = sender as PictureBox;
int addPoints = gamebox.Width;
txtPoints.Text = (Convert.ToInt32(txtPoints.Text) + addPoints).ToString();
if ((Convert.ToInt32(txtBiggestBox.Text) < addPoints))
{
txtBiggestBox.Text = (Convert.ToString(addPoints));
}
pnlSpiel.Controls.Remove(sender as PictureBox);
}
private void button1_Click_1(object sender, EventArgs e)
{
if (tmrEasterEgg.Enabled)
{
tmrEasterEgg.Stop();
BackColor = Color.LightGray;
}
else
{
tmrEasterEgg.Start();
}
}
private void tmrEasterEgg_Tick(object sender, EventArgs e)
{
Color randomColor = Color.FromArgb(rndColor.Next(256), rndColor.Next(256), rndColor.Next(256));
BackColor = randomColor;
}
private void tmrResize_Tick(object sender, EventArgs e)
{
for (int i = 0; i < pnlSpiel.Controls.Count; i++)
{
PictureBox gamebox = pnlSpiel.Controls[i] as PictureBox;
gamebox.Size = new Size(gamebox.Size.Width + 1, gamebox.Size.Height + 1);
}
}
private void btnReset_Click(object sender, EventArgs e)
{
pnlSpiel.Controls.Clear();
txtNotification.Text = "Das Spiel wurde zurückgesetzt";
txtPoints.Text = "0";
btnStart.Visible = true;
}
}
}
You can have the collision detection in your CreateBox method. And decide whether to add the object or not in there.
Like this:
private void CreateBox()
{
Rectangle bounds = new Rectangle(rndCreation.Next(0, pnlSpiel.Width - 30),
rndCreation.Next(0, pnlSpiel.Height - 30),
20, 20);
bool pBDoIntersect = false;
foreach (Control picturebox in pnlSpiel.Controls)
{
if (bounds.IntersectsWith(picturebox.Bounds))
{
pBDoIntersect = true;
}
}
if (!pBDoIntersect)
{
PictureBox gamebox = new PictureBox();
gamebox.Size = new Size(bounds.Width, bounds.Height);
gamebox.Location = new Point(bounds.X, bounds.Y);
gamebox.BackColor = Color.FromArgb(rndCreation.Next(0, 255), rndCreation.Next(0, 255), rndCreation.Next(0, 255));
pnlSpiel.Controls.Add(PB);
gamebox.Click += pictureBox1_Click;
}
else
{
// spawn in another place?
}
}

How to connect pictureboxes with connecting line

first sorry for my English. I am programming application in windows forms. It is something like Packet Tracer. I have four buttons. When I click on them, they dynamicaly create pictureboxes with picture of Router or Switch,.... Each time I click on the button, new picture box(Switch or Router,...), is created. I can also move with this pictureboxes by mouse.
I need to create a button, which connects selected pictureboxes with line(Cable). This pictureboxes should be selected by click on them. It sholud be able to move with this objects(movable line).
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int a = 0;
int b = 0;
int c = 0;
int d = 0;
PictureBox[] picturebox = new PictureBox[100];
public Form1()
{
InitializeComponent();
}
private void router_Click(object sender, EventArgs e)
{
++a;
picturebox[a] = new PictureBox();
picturebox[a].Name = "picturebox" + a;
picturebox[a].Location = new Point(0 + (a-1) *100,100);
picturebox[a].Size = new Size(70, 70);
picturebox[a].BorderStyle = BorderStyle.None;
picturebox[a].SizeMode = PictureBoxSizeMode.StretchImage;
this.Controls.Add(picturebox[a]);
picturebox[a].Image = Image.FromFile(#"D:\\router.jpg");
picturebox[a].Refresh();
picturebox[a].MouseDown += new MouseEventHandler(picMouseDown);
picturebox[a].MouseMove += new MouseEventHandler(picMouseMove);
picturebox[a].MouseUp += new MouseEventHandler(picMouseUp);
}
private void Form1_Load(object sender, EventArgs e)
{
}
int x = 0;
int y = 0;
bool drag = false;
private void picMouseDown(object sender, MouseEventArgs e)
{
// Get original position of cursor on mousedown
x = e.X;
y = e.Y;
drag = true;
}
private void picMouseMove(object sender, MouseEventArgs e)
{
if (drag)
{
PictureBox pb = (PictureBox)sender;
// Get new position of picture
pb.Top += e.Y - y;
pb.Left += e.X - x;
pb.BringToFront();
}
}
private void picMouseUp(object sender, MouseEventArgs e)
{
drag = false;
}
private void switch1_Click(object sender, EventArgs e)
{
++b;
picturebox[b] = new PictureBox();
picturebox[b].Name = "picturebox" + b;
picturebox[b].Location = new Point(0 + (b - 1) * 100, 180);
picturebox[b].Size = new Size(70, 70);
picturebox[b].BorderStyle = BorderStyle.None;
picturebox[b].SizeMode = PictureBoxSizeMode.StretchImage;
this.Controls.Add(picturebox[b]);
picturebox[b].Image = Image.FromFile(#"D:\HP ProBook 450\Desktop\Grafika\switch1.png");
picturebox[b].Refresh();
picturebox[b].MouseDown += new MouseEventHandler(picMouseDown);
picturebox[b].MouseMove += new MouseEventHandler(picMouseMove);
picturebox[b].MouseUp += new MouseEventHandler(picMouseUp);
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void pc_Click(object sender, EventArgs e)
{
++c;
picturebox[c] = new PictureBox();
picturebox[c].Name = "picturebox" + c;
picturebox[c].Location = new Point(0 + (c - 1) * 100, 260);
picturebox[c].Size = new Size(70, 70);
picturebox[c].BorderStyle = BorderStyle.None;
picturebox[c].SizeMode = PictureBoxSizeMode.StretchImage;
this.Controls.Add(picturebox[c]);
picturebox[c].Image = Image.FromFile(#"D:\HP ProBook 450\Desktop\pc.jpg");
picturebox[c].Refresh();
picturebox[c].MouseDown += new MouseEventHandler(picMouseDown);
picturebox[c].MouseMove += new MouseEventHandler(picMouseMove);
picturebox[c].MouseUp += new MouseEventHandler(picMouseUp);
}
private void server_Click(object sender, EventArgs e)
{
++d;
picturebox[d] = new PictureBox();
picturebox[d].Name = "picturebox" + d;
picturebox[d].Location = new Point(0 + (d - 1) * 100, 340);
picturebox[d].Size = new Size(70, 70);
picturebox[d].BorderStyle = BorderStyle.None;
picturebox[d].SizeMode = PictureBoxSizeMode.StretchImage;
this.Controls.Add(picturebox[d]);
picturebox[d].Image = Image.FromFile(#"D:\HP ProBook 450\Desktop\server.png");
picturebox[d].Refresh();
picturebox[d].MouseDown += new MouseEventHandler(picMouseDown);
picturebox[d].MouseMove += new MouseEventHandler(picMouseMove);
picturebox[d].MouseUp += new MouseEventHandler(picMouseUp);
}
}
}
THank you for your help.
You need to invalidate the parent when you add a picturebox or when you move a picturebox:
(picMouseMove and 4 times in the click handlers, it would be better to use 1 function)
Invalidate();
This is an example OnPaint, drawing lines between the pictureboxes as they are located in the Controls collection: (your picturebox array seems very weird, you always add controls at index 1, always overwriting the previous entry?! i'd suggest using a List if you need to keep a reference to them)
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var pictureBoxes = Controls.OfType<PictureBox>().ToArray();
if (pictureBoxes.Length > 1)
{
for (int i = 1; i < pictureBoxes.Length; i++)
{
DrawLineBetween(e.Graphics, pictureBoxes[i - 1], pictureBoxes[i]);
}
}
}
This function can be used to draw a line between 2 of your boxes:
private void DrawLineBetween(Graphics g, PictureBox from, PictureBox to)
{
g.DrawLine(Pens.Black,
new Point(from.Left + from.Width / 2, from.Top + from.Height / 2),
new Point(to.Left + to.Width / 2, to.Top + to.Height / 2));
}
----- full sample below -----
I refactored your full example, and added the code above to start you off with a working example:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
List<PictureBox> pictureboxes = new List<PictureBox>();
public Form1()
{
InitializeComponent();
}
private void AddPictureBox(string imagePath)
{
var pb = new PictureBox();
pb.Name = "picturebox" + pictureboxes.Count;
pb.Location = new Point(pictureboxes.Count * 100, 100);
pb.Size = new Size(70, 70);
pb.BorderStyle = BorderStyle.None;
pb.SizeMode = PictureBoxSizeMode.StretchImage;
this.Controls.Add(pb);
pb.Image = Image.FromFile(imagePath);
pb.Refresh();
pb.MouseDown += new MouseEventHandler(picMouseDown);
pb.MouseMove += new MouseEventHandler(picMouseMove);
pb.MouseUp += new MouseEventHandler(picMouseUp);
pictureboxes.Add(pb);
Invalidate();
}
private void router_Click(object sender, EventArgs e)
{
AddPictureBox(#"D:\\router.jpg");
}
private void Form1_Load(object sender, EventArgs e)
{
}
int x = 0;
int y = 0;
bool drag = false;
private void picMouseDown(object sender, MouseEventArgs e)
{
// Get original position of cursor on mousedown
x = e.X;
y = e.Y;
drag = true;
}
private void picMouseMove(object sender, MouseEventArgs e)
{
if (drag)
{
PictureBox pb = (PictureBox)sender;
// Get new position of picture
pb.Top += e.Y - y;
pb.Left += e.X - x;
pb.BringToFront();
Invalidate();
}
}
private void picMouseUp(object sender, MouseEventArgs e)
{
drag = false;
}
private void switch1_Click(object sender, EventArgs e)
{
AddPictureBox(#"D:\HP ProBook 450\Desktop\Grafika\switch1.png");
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void pc_Click(object sender, EventArgs e)
{
AddPictureBox(#"D:\HP ProBook 450\Desktop\pc.jpg");
}
private void server_Click(object sender, EventArgs e)
{
AddPictureBox(#"D:\HP ProBook 450\Desktop\server.png");
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (pictureboxes.Count > 1)
{
var arr = pictureboxes.ToArray();
for (int i = 1; i < arr.Length; i++)
{
DrawLineBetween(e.Graphics, arr[i - 1], arr[i]);
}
}
}
private void DrawLineBetween(Graphics g, PictureBox from, PictureBox to)
{
g.DrawLine(Pens.Black,
new Point(from.Left + from.Width / 2, from.Top + from.Height / 2),
new Point(to.Left + to.Width / 2, to.Top + to.Height / 2));
}
}
}

How to print the content of a panel with RadPrintPreview?

i want print the content of panel with RadPrintPreview of telerik , but when i declare RadPrintDocument i cant associat this later with panel !
this is my code :
private void doc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Bitmap bmp = new Bitmap(radPanel2.Width, radPanel2.Height, radPanel2.CreateGraphics());
radPanel2.DrawToBitmap(bmp, new Rectangle(0, 0, radPanel2.Width, radPanel2.Height));
RectangleF bounds = e.PageSettings.PrintableArea;
e.Graphics.DrawImage(bmp, bounds.Left, bounds.Top, radPanel2.Width, radPanel2.Height);
}
private void btn_Imression_Click(object sender, EventArgs e)
{
System.Drawing.Printing.PrintDocument doc = new System.Drawing.Printing.PrintDocument();
doc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(doc_PrintPage);
RadPrintPreviewDialog PrintSettings = new RadPrintPreviewDialog();
PrintSettings.Document = doc;
PageSettings pgsetting = new PageSettings();
if (PrintSettings.ShowDialog() == DialogResult.OK)
doc.Print();
}
and thank's for help :)
In order to print Telerik UI for WinForms control, you should use the embedded in the framework functionality, namely RadPrintDocument, which allows you to print any object implementing the IPrintable interface. Here is how this can be done for RadPanel:
RadPanel panel = new RadPanel();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
InitializeComponent();
panel.Dock = DockStyle.Fill;
panel.BackColor = Color.Red;
panel.Parent = this;
RadButton b = new RadButton();
b.Text = "button1";
panel.Controls.Add(b);
RadButton b2 = new RadButton();
b2.Text = "button1";
b2.Location = new Point(400, 400);
panel.Controls.Add(b2);
}
private class PanelPrinter : IPrintable
{
private RadPanel panel;
public PanelPrinter(RadPanel panel)
{
this.panel = panel;
}
public int BeginPrint(RadPrintDocument sender, PrintEventArgs args)
{
return 1;
}
public bool EndPrint(RadPrintDocument sender, PrintEventArgs args)
{
return false;
}
public Form GetSettingsDialog(RadPrintDocument document)
{
return null;
}
public bool PrintPage(int pageNumber, RadPrintDocument sender, PrintPageEventArgs args)
{
float scale = Math.Min((float)args.MarginBounds.Width / panel.Size.Width, (float)args.MarginBounds.Height / panel.Size.Height);
Bitmap panelBmp = new Bitmap(this.panel.Width, this.panel.Height);
this.panel.DrawToBitmap(panelBmp, this.panel.Bounds);
Matrix saveMatrix = args.Graphics.Transform;
args.Graphics.ScaleTransform(scale, scale);
args.Graphics.DrawImage(panelBmp, args.MarginBounds.Location);
args.Graphics.Transform = saveMatrix;
return false;
}
}
private void radButton1_Click(object sender, EventArgs e)
{
RadPrintDocument document = new RadPrintDocument();
document.AssociatedObject = new PanelPrinter(this.panel);
RadPrintPreviewDialog dialog = new RadPrintPreviewDialog(document);
dialog.ShowDialog();
}

Categories