print marigin not set in second page - c#

private StringReader myReader;
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
printDialog1.Document = printDocument1;
string strText = this.richTextBox1.Text;
myReader = new StringReader(strText);
if (printDialog1.ShowDialog() == DialogResult.OK)
{
printDocument1.Print();
}
}
private void printPrieviewToolStripMenuItem_Click(object sender, EventArgs e)
{
string strText = this.richTextBox1.Text;//read text for richtextbox
myReader = new StringReader(strText);
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
string line = null;
Font printFont = new System.Drawing.Font("Times New Roman", 8, FontStyle.Regular);
SolidBrush myBrush = new SolidBrush(Color.Black);
float linesPerPage = 0;
float topMargin = 590;
float yPosition = 590;
int count = 0;
float leftMargin = 70;
linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics);
while (count < linesPerPage && ((line = myReader.ReadLine()) != null))
{
if (count == 0)
{
yPosition = 590;
topMargin = 590;
}
else
{
yPosition = 100;
topMargin = 100;
}
yPosition = topMargin + (count * printFont.GetHeight(e.Graphics));
e.Graphics.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
count++;
}
if (line != null)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
myBrush.Dispose();
}
}
}
}
please where is my mistake.i want to print first page is top marigin is 590,and if more pages second page should be print top marigin is 100.
above given code is printing is ok but print marigin is not solved
help me the corection.

You are setting top margin based on count but count is not a page count, it is a line count. you need to keep a page count and use that.

Use a field to hold if it's the first page, remember to set it to true before calling printDocument1_PrintPage e.g:
bool Isfirstpage = true;
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
///.....
if (count == 0 && Isfirstpage)
{
yPosition = 590;
topMargin = 590;
Isfirstpage = false;
}
///....

Related

Infinite pages generated with e.HasMorePages

I generate several QRCodes and would like to print the barcodes one after another on an A4 size page in Print Preview Control. I also use this control: PrintBar
I calculated, that about 5 QRCodes can be on an A4 format page, so I tried to split with HasMorePages.
Print Preview without HasMorePages: the A4 page with the QRCodes screenshot - the last QRCode should be on the last page.
I added e.HasMorePages and return, but is not working correctly...It counts the pages to infinite and after that crashes.
My code:
BeginPrint
private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
this.currentItem = 0;
}
PrintPage
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
String fontName = "Arial";
Font fontNormal = new Font(fontName, 12, System.Drawing.FontStyle.Regular);
float itemHeight = fontNormal.GetHeight(e.Graphics);
Brush normalColour = Brushes.Black;
float leftMargin = e.MarginBounds.Left;
float topMargin = e.MarginBounds.Top;
float printWidth = e.MarginBounds.Width;
float printHeight = e.MarginBounds.Height;
float rightMargin = leftMargin + printWidth;
float currentPosition = topMargin;
float numberWidth = 70;
float lineWidth = printWidth - numberWidth;
float lineLeft = leftMargin;
float numberLeft = leftMargin + lineWidth;
int items = 0;
foreach (DataRow dr in dt.Rows)
{
if (!dr[4].Equals(""))
items += Convert.ToInt32(dr[4].ToString());
else
items += 0;
}
noOfItems = items;
foreach (DataRow dr in dt.Rows)
{
Bitmap bt = null;
if (!dr[1].Equals(""))
{
if (!dr[4].Equals(""))
{
int nrcodes = Convert.ToInt32(dr[4].ToString());//in the 4th row the value means how many QRCodes should be generated
for (int i = 0; i < nrcodes; i++)
{
if (i % 5 != 0)
{
bt = GenerateQRCODE(dr[1].ToString());//dr[1] QRCode value
e.Graphics.DrawImage(bt, leftMargin, currentPosition, 200, 200);
e.Graphics.DrawString(dr[1].ToString(), fontNormal, normalColour, leftMargin + 40, currentPosition + 180); //dr[1] - text under QR Code
}
else
{
e.HasMorePages = true;
return;
}
currentPosition += 200;
}
}
}
}
// e.HasMorePages = true;
}
Yes, I need to print the same QR Code as many times as in the dr[4] column value. After that the next QR Code the same way.
In this case you need to keep track of the current DataRow and n copy to not repeat the same code for the same row and copy when you set e.HasMorePages = true;. For the copies, request a new page if the bottom of the current output block exceeds the e.MarginBounds.Bottom. To request a new page for each row, uncomment the last lines of the following example.
// +
using System.Drawing.Printing;
// ...
private int curRow = 0;
private int curCopy = 0;
// Or from where you call `.Print();`
// Button.Click event for example.
private void printDocument1_BeginPrint(object sender, PrintEventArgs e)
{
curRow = 0;
curCopy = 0;
}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
var curY = e.MarginBounds.Y;
using (var fontNormal = new Font("Arial", 12))
using (var sf = new StringFormat())
{
sf.Alignment = sf.LineAlignment = StringAlignment.Center;
int itemHeight = (int)fontNormal.GetHeight(e.Graphics) + 10;
for (int row = curRow; row < dt.Rows.Count; row++)
{
DataRow dr = dt.Rows[row];
if (!string.IsNullOrEmpty(dr.Field<string>(1)) &&
int.TryParse(dr.Field<string>(4)?.ToString(), out int copies))
{
for (int i = curCopy; i < copies; i++)
{
var imgRect = new Rectangle(e.MarginBounds.X, curY, 200, 200);
var labelRect = new Rectangle(
imgRect.X,
imgRect.Bottom,
imgRect.Width,
itemHeight);
if (curY + imgRect.Height + labelRect.Height >= e.MarginBounds.Bottom)
{
curCopy = i;
e.HasMorePages = true;
return;
}
using (var qrImage = GenerateQRCODE(dr[1].ToString()))
e.Graphics.DrawImage(qrImage, imgRect);
e.Graphics.DrawString(dr[1].ToString(),
fontNormal, Brushes.Black,
labelRect, sf);
curY = labelRect.Bottom + 30;
}
}
curRow = row + 1;
curCopy = 0;
// Uncomment if you want to start a new
// page for each row.
//if (row < dt.Rows.Count - 1)
//{
// e.HasMorePages = true;
// break;
//}
}
}

Picturebox duplicating value

I am working on a little program that starts taking pictures in the moment you click on a button. Also it can be ended earlier clicking another button.
The little bug that I am having is that I use a timer to process each time you go throw it since you hit the start button in a 1000ms interval, the problem comes when the first process finishes, the next process you start will duplicate the value of a progressbar x2 forever until you close the app.
namespace Fotos
{
public partial class Fotos : Form
{
private static string Path = #"C:\Fotos\";
//private static string Agua = #"C:\Marca de Agua\";
private bool HayDispositivos, terminado;
private string nombre;
private int i = 0, j = 0, z = 0, eleccion;
private FilterInfoCollection MisDispositivos;
private VideoCaptureDevice miWebcam;
private MagickImageCollection gif = new MagickImageCollection();
public Fotos()
{
InitializeComponent();
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
private void Creador()
{
CreacionGif cg = new CreacionGif(gif, nombre);
cg.ShowDialog();
}
private void MarcaAgua(PictureBox picturebox1)
{
RectangleF angulo = new RectangleF(1350, 975, 535, 90); //rectf for My Text
using (Graphics g = Graphics.FromImage(picturebox1.Image))
{
//g.DrawRectangle(new Pen(Color.Red, 2), 655, 460, 535, 90);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
g.DrawString(DateTime.Now.ToString(), new Font("Tahoma", 32, FontStyle.Bold), Brushes.White, angulo, sf);
EncoderParameters myEncoderParameters = new EncoderParameters(1);
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
Encoder myEncoder = Encoder.Quality;
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 30L);
myEncoderParameters.Param[0] = myEncoderParameter;
if (progressBar1.Value == 0)
{
j = 0;
}
picturebox1.Image.Save(Path + textBoxNombreFoto.Text + "_" + i + ".jpg", jpgEncoder, myEncoderParameters);
gif.Add(Path + textBoxNombreFoto.Text + "_" + i + ".jpg");
gif[j].AnimationDelay = 200;
j++;
g.Dispose();
sf.Dispose();
/* using (Image image = pictureBox1.Image)
using (Image watermarkImage = Image.FromFile(Agua +"fecha.jpg"))
using (Graphics imageGraphics = Graphics.FromImage(image))
using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))
{
int x = (image.Width / 2 - watermarkImage.Width / 2);
int y = (image.Height / 2 - watermarkImage.Height / 2);
watermarkBrush.TranslateTransform(x, y);
imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width + 1, watermarkImage.Height)));
image.Save(Path + i +".jpg");*/
}
}
private void Form_Load(object sender, EventArgs e)
{
CargaDispositivos();
}
public void CargaDispositivos()
{
MisDispositivos = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (MisDispositivos.Count > 0)
{
HayDispositivos = true;
for (int i = 0; i < MisDispositivos.Count; i++)
comboBox1.Items.Add(MisDispositivos[i].Name.ToString());
comboBox1.Text = MisDispositivos[0].Name.ToString();
}
else HayDispositivos = false;
}
private void CerrarWebcam()
{
if (miWebcam != null && miWebcam.IsRunning)
{
miWebcam.SignalToStop();
miWebcam = null;
}
}
private void Capturando(object sender, NewFrameEventArgs eventArgs)
{
if(terminado == false)
{
Bitmap Imagen = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = Imagen;
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
CerrarWebcam();
}
private void foto_Click(object sender, EventArgs e)
{
if (miWebcam != null && miWebcam.IsRunning && (radioButton1.Checked == true || radioButton2.Checked == true) && textBoxNombreFoto.TextLength > 0)
{
timer1.Enabled = true;
timer1.Start();
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timer1_Tick);
terminado = false;
if(radioButton1.Checked == true)
{
eleccion = 18;
progressBar1.Maximum = 1800;
}
else
{
eleccion = 36;
progressBar1.Maximum = 3600;
}
}
else
{
MessageBox.Show("Por favor revisa que todos los campos estén rellenos");
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
CerrarWebcam();
int i = comboBox1.SelectedIndex;
string nombreVideo = MisDispositivos[i].MonikerString;
miWebcam = new VideoCaptureDevice(nombreVideo);
miWebcam.NewFrame += new NewFrameEventHandler(Capturando);
miWebcam.Start();
}
private void finFoto_Click(object sender, EventArgs e)
{
MarcaAgua(pictureBox1);
terminado = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (progressBar1.Value % 30 == 0 && progressBar1.Value <= eleccion && terminado != true || progressBar1.Value == 0)
{
miWebcam.NewFrame += new NewFrameEventHandler(Capturando);
MarcaAgua(pictureBox1);
z++;
}
if (progressBar1.Value < eleccion && terminado != true)
{
progressBar1.Value++;
i++;
}
textBoxTiempo.Text = progressBar1.Value.ToString();
textBoxTiempo.Update();
if ((terminado == true || progressBar1.Value >= eleccion) && i!=0)
{
timer1.Stop();
timer1.Dispose();
progressBar1.Dispose();
progressBar1.Value = 0;
nombre = textBoxNombreFoto.Text;
Creador();
i = 0;
MessageBox.Show("Proceso Terminado con Éxito");
}
}

Getting values from mouse hover on a class object C#

I've a txt file with a 360 numbers, I must read all of these and draw a kind of Disc made of FillPie eachone colored in scale of grey due to the value of the list. Until here everything is quite simple.I made a class with the data(value in the txt and degree) of one single fillpie with a Paint method that draw it of the correct color.
this is the code of the class:
class DatoDisco
{
int valoreSpicchio;
int gradi;
public DatoDisco(int valoreTastatore, int gradiLettura)
{
valoreSpicchio = valoreTastatore;
gradi = gradiLettura;
}
public void Clear()
{
valoreSpicchio = 0;
gradi = 0;
}
private int ScalaGrigi()
{
int grigio = 0;
if (valoreSpicchio <= 0)
{
grigio = 125 + (valoreSpicchio / 10);
if (grigio < 0)
grigio = 0;
}
if (valoreSpicchio > 0)
{
grigio = 125 + (valoreSpicchio / 10);
if (grigio > 230)
grigio = 230;
}
return grigio;
}
public void Paint (Graphics grafica)
{
try
{
Brush penna = new SolidBrush(Color.FromArgb(255, ScalaGrigi(), ScalaGrigi(), ScalaGrigi()));
grafica.FillPie(penna, 0, 0, 400, 400, gradi, 1.0f);
}
catch
{
}
}
public int ValoreSpicchio
{
get
{
return valoreSpicchio;
}
}
public int Gradi
{
get
{
return gradi;
}
}
}
here is where I draw everything:
public partial class Samac : Form
{
libnodave.daveOSserialType fds;
libnodave.daveInterface di;
libnodave.daveConnection dc;
int rack = 0;
int slot = 2;
int scalaGrigi = 0;
int angolatura = 0;
List<int> valoriY = new List<int>();
//Disco disco = new Disco();
List<DatoDisco> disco = new List<DatoDisco>();
float[] valoriTastatore = new float[360];
public Samac()
{
InitializeComponent();
StreamReader dataStream = new StreamReader("save.txt");
textBox1.Text = dataStream.ReadLine();
dataStream.Dispose();
for (int i = 0; i <= 360; i++ )
chart1.Series["Series2"].Points.Add(0);
//AggiornaGrafico(textBox1.Text, chart1);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
}
string indirizzoIpPlc
{
get
{
FileIniDataParser parser = new FileIniDataParser();
IniData settings = parser.LoadFile("config.ini");
return settings["PLC_CONNECTION"]["PLC_IP"];
}
}
private void AggiornaGrafico(string nomeFile, Chart grafico, bool online)
{
int max = 0;
int min = 0;
grafico.Series["Series1"].Points.Clear();
grafico.Series["Series2"].Points.Clear();
grafico.Series["Series3"].Points.Clear();
grafico.Series["Series4"].Points.Clear();
grafico.ChartAreas[0].AxisX.Maximum = 360;
grafico.ChartAreas[0].AxisX.Minimum = 0;
grafico.ChartAreas[0].AxisY.Maximum = 500;
grafico.ChartAreas[0].AxisY.Minimum = -500;
String file = nomeFile;
valoriY.Clear();
disco.Clear();
if (online == false)
{
System.IO.File.WriteAllText("save.txt", nomeFile);
}
StreamReader dataStreamGrafico = new StreamReader(file);
StreamReader dataStreamScheda = new StreamReader("Scheda.sch");
string datasample;
string[] scheda = new string[56];
for (int i = 0; i < 56; i++)
{
scheda[i] = dataStreamScheda.ReadLine();
}
dataStreamScheda.Close();
int gradi = 1;
while ((datasample = dataStreamGrafico.ReadLine()) != null)
{
grafico.Series["Series2"].Points.Add(0);
grafico.Series["Series2"].Color = Color.Red;
grafico.Series["Series2"].BorderWidth = 3;
grafico.Series["Series3"].Points.Add(Convert.ToInt32(float.Parse(scheda[5])));
grafico.Series["Series3"].Color = Color.Green;
grafico.Series["Series3"].BorderWidth = 3;
grafico.Series["Series4"].Points.Add(Convert.ToInt32(-float.Parse(scheda[5])));
grafico.Series["Series4"].Color = Color.Green;
grafico.Series["Series4"].BorderWidth = 3;
grafico.Series["Series1"].Points.Add(int.Parse(datasample));
grafico.Series["Series1"].BorderWidth = 5;
valoriY.Add(int.Parse(datasample));
//disco.Add(int.Parse(datasample));
disco.Add(new DatoDisco(int.Parse(datasample), gradi));
gradi++;
}
dataStreamGrafico.Close();
max = Convert.ToInt32(chart1.Series["Series1"].Points.FindMaxByValue().YValues[0]);
min = Convert.ToInt32(chart1.Series["Series1"].Points.FindMinByValue().YValues[0]);
lblCampanatura.Text = (((float)max + min) / 2000.0).ToString();
lblSbandieramento.Text = (((float)max - min) / 1000.0).ToString();
if ((Math.Abs(max) > 800) || (Math.Abs(min) > 800))
{
if (Math.Abs(max) >= Math.Abs(min))
{
chart1.ChartAreas[0].AxisY.Maximum = max + 200;
chart1.ChartAreas[0].AxisY.Minimum = -(max + 200);
}
else
{
chart1.ChartAreas[0].AxisY.Maximum = min + 200;
chart1.ChartAreas[0].AxisY.Minimum = -(min + 200);
}
}
else
{
chart1.ChartAreas[0].AxisY.Maximum = 800;
chart1.ChartAreas[0].AxisY.Minimum = -800;
}
boxGraficaDisco.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
if (result == DialogResult.OK)
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
ToolTip tooltip = new ToolTip();
private int lastX;
private int lastY;
private void chart1_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
int cursorX = Convert.ToInt32(chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X));
tooltip.Show("X:" + cursorX.ToString("0.00") + "Y:" + Convert.ToInt32(chart1.Series[0].Points[cursorX].YValues[0]).ToString(), this.chart1, e.Location.X + 20, e.Location.Y + 20);
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
private void button1_Click_1(object sender, EventArgs e)
{
int indice = ((int)Char.GetNumericValue(textBox1.Text[textBox1.Text.Length - 5]))+1;
if (File.Exists(textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt"))
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt";
try
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
catch
{
MessageBox.Show("Il File non esiste");
}
}
else
{
MessageBox.Show("Il File non esiste");
}
}
private void btnGrafMeno_Click(object sender, EventArgs e)
{
int indice = ((int)Char.GetNumericValue(textBox1.Text[textBox1.Text.Length - 5])) - 1;
if (indice >= 0)
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt";
try
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
catch
{
MessageBox.Show("Il File non esiste");
}
}
else
{
MessageBox.Show("Prima lettura disco");
}
}
private void btnConnetti_Click(object sender, EventArgs e)
{
fds.rfd = libnodave.openSocket(102, indirizzoIpPlc);
fds.wfd = fds.rfd;
if (fds.rfd > 0)
{
di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
di.setTimeout(1000000);
dc = new libnodave.daveConnection(di, 0, rack, slot);
int res = dc.connectPLC();
timer1.Start();
// AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
else
{
MessageBox.Show("Impossibile connettersi");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
int res;
res = dc.readBytes(libnodave.daveDB, 21, 40, 1, null);
if (res == 0)
{
var letturaDati = (dc.getS8At(0) & (1 << 0)) != 0;
if (letturaDati == true)
{
int puntatore = 30;
StreamWriter datiDisco = new StreamWriter("DatiDaPlc.csv");
datiDisco.WriteLine("X;" + "C;" + "Z;");
while (puntatore <= 10838)
{
res = dc.readBytes(libnodave.daveDB, 3, puntatore, 192, null);
if (res == 0)
{
for (int i = 0; dc.getU32At(i) != 0; i = i + 12)
{
datiDisco.Write(dc.getU32At(i).ToString() + ";");
datiDisco.Write(dc.getU32At(i + 4).ToString() + ";");
datiDisco.WriteLine(dc.getFloatAt(i + 8).ToString() + ";");
}
}
puntatore = puntatore + 192;
}
datiDisco.Close();
StreamReader lettura = new StreamReader("DatiDaPlc.csv");
StreamWriter scritt = new StreamWriter("Disco.csv");
var titolo = lettura.ReadLine();
var posizioneLettura = lettura.ReadLine();
var posX = posizioneLettura.Split(';');
int minX = Convert.ToInt32(posX[0]) - 5;
int maxX = Convert.ToInt32(posX[0]) + 5;
int contatore = 0;
while (!lettura.EndOfStream)
{
var line = lettura.ReadLine();
var values = line.Split(';');
if ((Convert.ToInt32(values[1]) >= contatore && Convert.ToInt32(values[1]) < contatore + 1000) && (Convert.ToInt32(values[0]) > minX && Convert.ToInt32(values[0]) <= maxX))
{
scritt.WriteLine(Convert.ToInt32(float.Parse(values[2]) * 1000).ToString());
contatore += 1000;
}
}
lettura.Close();
scritt.Close();
AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
}
else
{
timer1.Stop();
MessageBox.Show("Disconnesso");
dc.disconnectPLC();
di.disconnectAdapter();
fds.rfd = libnodave.closeSocket(102);
fds.wfd = fds.rfd;
}
}
}
private void btnDisconnetti_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
dc.disconnectPLC();
di.disconnectAdapter();
fds.rfd = libnodave.closeSocket(102);
fds.wfd = fds.rfd;
timer1.Stop();
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
private void Samac_FormClosing(object sender, FormClosingEventArgs e)
{
if (timer1.Enabled == true)
{
dc.disconnectPLC();
di.disconnectAdapter();
libnodave.closeSocket(102);
timer1.Stop();
}
}
private void button1_Click_2(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
else
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
private void chart2_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
int cursorX = Convert.ToInt32(chart2.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X));
int cursorY = Convert.ToInt32(chart2.ChartAreas[0].AxisY.PixelPositionToValue(e.Location.Y));
//tooltip.Show("X:" + chart2.Series[0].Points[cursorX].XValue.ToString() + "Y:" + chart2.Series[0].Points[cursorX].YValues[0].ToString(), this.chart2, e.Location.X + 20, e.Location.Y + 20);
tooltip.Show("X:" + cursorX.ToString() + "Y:#VALY" , this.chart2, e.Location.X + 20, e.Location.Y + 20);
//chart2.Series[0].ToolTip="#VALY";
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
private void boxGraficaDisco_Paint(object sender, PaintEventArgs e)
{
Graphics grafica = e.Graphics;
//disco.Paint(grafica);
foreach (DatoDisco d in disco)
{
d.Paint(grafica);
}
}
private void boxGraficaDisco_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
foreach (DatoDisco d in disco)
{
}
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
}
Now I need that when i go with the mouse over the drawn disc, a tooltip show me the data of the fillPie(degree and value of txt) but i can't figure out how.
Anyone can help me?
this is an image of the disc
Eventually it looks as if all you want is a function to get the angle between the mouse position and the center of the disc..
Here is a function to calculate an angle given two points:
double AngleFromPoints(Point pt1, Point pt2)
{
Point P = new Point(pt1.X - pt2.X, pt1.Y - pt2.Y);
double alpha = 0d;
if (P.Y == 0) alpha = P.X > 0 ? 0d : 180d;
else
{
double f = 1d * P.X / (Math.Sqrt(P.X * P.X + P.Y * P.Y));
alpha = Math.Acos(f) * 180d / Math.PI;
if (P.Y > 0) alpha = 360d - alpha;
}
return alpha;
}

fitting rich text box's text into print page c#

I am new in C# and I am trying to print richTextBox's text into a page with size 58x297 but the text always starts from the middle of the page. I checked the printer properties but I couldn't find anything wrong. My aim is to print the text of my rich text box at the very left and top point of the page. I believe the problem is the initial spacing because of the size of my page that is 58x297 spacing is normal for an A4 page but not for mine.
This is the piece of work that I am trying to make work
private void button1_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
PrintDocument documentToPrint = new PrintDocument();
printDialog.Document = documentToPrint;
if (printDialog.ShowDialog() == DialogResult.OK)
{
StringReader reader = new StringReader(richTextBox1.Text);
documentToPrint.OriginAtMargins = false;
documentToPrint.PrintPage += new PrintPageEventHandler(Document_Print);
documentToPrint.Print();
}
}
private void Document_Print(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
StringReader reader = new StringReader(richTextBox1.Text);
float LinesPerPage = 0;
float YPosition = 0;
int Count = 0;
float LeftMargin = e.MarginBounds.Left;
float TopMargin = e.MarginBounds.Top;
string Line = null;
Font PrintFont = this.richTextBox1.Font;
SolidBrush PrintBrush = new SolidBrush(Color.Black);
LinesPerPage = e.MarginBounds.Height / PrintFont.GetHeight(e.Graphics);
while (Count < LinesPerPage && ((Line = reader.ReadLine()) != null))
{
YPosition = LeftMargin + (Count * PrintFont.GetHeight(e.Graphics));
e.Graphics.DrawString(Line, PrintFont, PrintBrush, LeftMargin, YPosition, new StringFormat());
Count++;
}
if (Line != null)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
PrintBrush.Dispose();
}
It would definitely be great if you have any ideas about. Thanks a lot ...

read items from listbox

I have a listbox with 1 or more textfiles, which im going to print as commands.
but I dont know how to make the streamreader read from listbox ?
so far I got this.:
public void OutputBtn_Click(object sender, EventArgs e)
{
PrintDocument PrintD = new PrintDocument();
PrintD.PrintPage += new PrintPageEventHandler(this.PrintDocument_PrintPage);
StreamReader SR = new StreamReader("C:\\myfile.txt");
PrintD.Print();
}
is there enyway I can change "C:\myfile.txt" or do I have to use "foreach" ?
Do you want something like this? I don't fully understand the question
string[] fileEntries = Directory.GetFiles("C:\\temp\\").Where(p =>
p.EndsWith(".txt")).ToArray<string>();
foreach (string fileName in fileEntries)
{
lb.Items.Add(new ListItem(fileName, fileName);
}
Ok so you have the listbox filled with filenames?
private StreamReader sr;
public void OutputBtn_Click(object sender, EventArgs e)
{
foreach(var li in lb.Items)
{
PrintDocument PrintD = new PrintDocument();
PrintD.PrintPage += new PrintPageEventHandler(this.PrintDocument_PrintPage);
sr = new StreamReader(li.ToString());
PrintD.Print();
}
}
private void PrintDocument_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
String line = null;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics) ;
// Iterate over the file, printing each line.
while (count < linesPerPage && ((line = sr.ReadLine()) != null))
{
yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString (line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}

Categories