click event prints all pages instead print range - c#

I have the following code for my BeginPrint, PrintPage and Click event. Firing the click event, its printing all pages. I would like to add a print range on button event that prints from-to range:
BeginPrint:
private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
curRow = 0;
curCopy = 0;
if (printrange)
{
((PrintDocument)sender).PrinterSettings.PrintRange = PrintRange.SomePages;
((PrintDocument)sender).PrinterSettings.FromPage = 1;
((PrintDocument)sender).PrinterSettings.ToPage = 1;
printrange = false;
}
}
PrintPage :
I'm generating QRCodes, borders and text in this method. Usually I have more than 2 pages with QRCodes. The problem is that it prints all pages
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
var curY = e.MarginBounds.Y;
var curX = e.MarginBounds.X + 30;//+ 10
Pen pen = new Pen(System.Drawing.ColorTranslator.FromHtml("#FFBD2D"), 1);
using (var fontNormal = new Font("Arial", 10))
using (var sf = new StringFormat())
{
sf.Alignment = sf.LineAlignment = StringAlignment.Center;
int itemHeight = (int)fontNormal.GetHeight(e.Graphics);
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(curX, curY, 156, 156);//e.MarginBounds.X
var labelRect = new Rectangle(
imgRect.X+180+20,//eltol
imgRect.Bottom-162,
itemHeight,
imgRect.Width);
using (var qrImage = GenerateQRCODE(dr[1].ToString()))
{
e.Graphics.DrawImage(RotateImage(qrImage, -90), imgRect);
}
SizeF labelSize = e.Graphics.MeasureString(dr[1].ToString(), fontNormal);
Bitmap stringmap = new Bitmap((int)labelSize.Height + 1, (int)labelSize.Width + 1);
Graphics gbitmap = Graphics.FromImage(stringmap);
gbitmap.TranslateTransform(0, labelSize.Width);
gbitmap.RotateTransform(-90);
gbitmap.DrawString(dr[1].ToString(), fontNormal, Brushes.Black, new PointF(0, 0), new StringFormat());
e.Graphics.DrawImage(stringmap, labelRect);
gbitmap.Dispose();
stringmap.Dispose();
e.Graphics.DrawLine(pen, curX, curY, curX, curY + 156);//57 |<
e.Graphics.DrawLine(pen, curX, curY + 156 , curX + 156 + 220, curY + 156);// _
e.Graphics.DrawLine(pen, curX + 156 + 220, curY + 156, curX + 156 + 220, curY);// >|
e.Graphics.DrawLine(pen, curX, curY, curX + 156 + 220, curY);// -
curX = imgRect.Right + 230; //horizontal gap
if (curX + imgRect.Width > e.MarginBounds.Right)
{
curX = e.MarginBounds.X + 30;
curY = labelRect.Bottom + 30;//55vertical gap
}
if (curY + imgRect.Height >= e.MarginBounds.Bottom)
{
curCopy = i + 1;
e.HasMorePages = true;
return;
}
}
}
curRow = row + 1;
curCopy = 0;
}
}
refreshprintbtn.Enabled = true;
printdialogbtn.Enabled = true;
}
In this click event I'm calling the print() method:
bool printrange = false;
private void printrangebtn_Click(object sender, EventArgs e)
{
printrange = true;
printDocument1.BeginPrint += printDocument1_BeginPrint;
printDocument1.PrintPage += printDocument1_PrintPage;
printDocument1.Print();
}
Thanks

You forgot to implement the PrintRange part in the PrintPage event. Just setting the PrintRange, FromPage, and ToPage properties doesn't mean that the printer knows which page should start with and which one should be the last. These properties exist to get the user inputs through the print dialogs or some setter methods and you need to use them as factors in your implementation.
For example, in PrintRange.SomePages case, use a class field to determine the target pages to print. Increment the field and print only if the value is within the .From and .To range.
// +
System.Drawing;
using System.Drawing.Printing;
// ...
private int curRow, curCopy, curPage;
public YourForm()
{
InitializeComponent();
printDocument1.BeginPrint += printDocument1_BeginPrint;
printDocument1.PrintPage += printDocument1_PrintPage;
}
private void printrangebtn_Click(object sender, EventArgs e)
{
printDocument1.PrinterSettings.PrintRange = PrintRange.SomePages;
printDocument1.PrinterSettings.FromPage = 1;
printDocument1.PrinterSettings.ToPage = 2;
printDocument1.Print();
}
private void printDocument1_BeginPrint(object sender, PrintEventArgs e)
{
curRow = 0;
curCopy = 0;
curPage = 0;
// ...
}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
var curY = e.MarginBounds.Y;
var curX = e.MarginBounds.X + 30;//+ 10
var doc = sender as PrintDocument;
using (var pen = new Pen(ColorTranslator.FromHtml("#FFBD2D")))
using (var fontNormal = new Font("Arial", 10))
using (var sf = new StringFormat())
{
sf.Alignment = sf.LineAlignment = StringAlignment.Center;
int itemHeight = (int)fontNormal.GetHeight(e.Graphics);
for (int row = curRow; row < dt.Rows.Count; row++)
{
curPage++;
var doPrint = doc.PrinterSettings.PrintRange != PrintRange.SomePages ||
(curPage >= doc.PrinterSettings.FromPage && curPage <= doc.PrinterSettings.ToPage);
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(curX, curY, 156, 156);//e.MarginBounds.X
var labelRect = new Rectangle(
imgRect.X + 180 + 20,//eltol
imgRect.Bottom - 162,
itemHeight,
imgRect.Width);
// If not, don't print and continue the calculations...
if (doPrint)
{
using (var qrImage = GenerateQRCODE(dr[1].ToString()))
e.Graphics.DrawImage(RotateImage(qrImage, -90), imgRect);
SizeF labelSize = e.Graphics.MeasureString(dr[1].ToString(), fontNormal);
Bitmap stringmap = new Bitmap((int)labelSize.Height + 1, (int)labelSize.Width + 1);
Graphics gbitmap = Graphics.FromImage(stringmap);
gbitmap.TranslateTransform(0, labelSize.Width);
gbitmap.RotateTransform(-90);
gbitmap.DrawString(dr[1].ToString(), fontNormal, Brushes.Black, new PointF(0, 0), new StringFormat());
e.Graphics.DrawImage(stringmap, labelRect);
gbitmap.Dispose();
stringmap.Dispose();
e.Graphics.DrawLine(pen, curX, curY, curX, curY + 156);//57 |<
e.Graphics.DrawLine(pen, curX, curY + 156, curX + 156 + 220, curY + 156);// _
e.Graphics.DrawLine(pen, curX + 156 + 220, curY + 156, curX + 156 + 220, curY);// >|
e.Graphics.DrawLine(pen, curX, curY, curX + 156 + 220, curY);// -
}
curX = imgRect.Right + 230; //horizontal gap
if (curX + imgRect.Width > e.MarginBounds.Right)
{
curX = e.MarginBounds.X + 30;
curY = labelRect.Bottom + 30;//55vertical gap
}
if (curY + imgRect.Height >= e.MarginBounds.Bottom)
{
if (!doPrint) break;
curCopy = i + 1;
e.HasMorePages = true;
return;
}
}
}
if (!doPrint)
{
curX = e.MarginBounds.X;
curY = e.MarginBounds.Y;
}
curRow = row + 1;
curCopy = 0;
}
}
refreshprintbtn.Enabled = true;
printdialogbtn.Enabled = true;
}
Side Notes
You shouldn't add handlers for the PrintDocument events each time you click a Button unless you remove the current handlers first in the EndPrint for example. Just add them once as shown in the Form's ctor or Load event.
System.Drawing.Pen is a disposable object so you need to dispose of it as well. Create it with the using statement or pass an instance using (pen) ... or call the .Dispose(); method explicitly. Do the same for any object implements the IDisposable interface.

Related

DrawPolygon() erases the old polygon when drawing

I set the points and when the points of the same color form a square, I draw a polygon. But when a new square is formed, the old one disappears.
can you tell me how to make sure that when drawing a new polygon, the old one does not disappear?
in the checkpoint() function, I check whether there is a square of points of the same color and return e coordinates for drawing.
public partial class Form1 : Form
{
private Class1 Class1 = new Class1();
private CellState currentPlayer = CellState.Red;
public const int SIZE = 11;
public const int Icon_Size = 30;
public Form1()
{
InitializeComponent();
}
//ставит точки
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
var p = new Point((int)Math.Round(1f * e.X / Icon_Size), (int)Math.Round(1f * e.Y / Icon_Size));
if (Class1[p] == CellState.Empty)
{
Class1.SetPoint(p, currentPlayer);
currentPlayer = Class1.Inverse(currentPlayer);
Invalidate();
}
}
//рисуем
private void OnPaint(object sender, PaintEventArgs e)
{
e.Graphics.ScaleTransform(Icon_Size, Icon_Size);
//рисуем сеточку
using (var pen = new Pen(Color.Gainsboro, 0.1f))
{
for (int x = 1; x < SIZE; x++)
e.Graphics.DrawLine(pen, x, 1, x, SIZE - 1);
for (int y = 1; y < SIZE; y++)
e.Graphics.DrawLine(pen, 1, y, SIZE - 1, y);
}
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//рисуем точки
using (var brush = new SolidBrush(Color.White))
for (int x = 1; x < Form1.SIZE; x++)
for (int y = 1; y < Form1.SIZE; y++)
{
var p = new Point(x, y);
var cell = Class1[p];
if (cell != CellState.Empty)
{
brush.Color = StateToColor(cell);
e.Graphics.FillEllipse(brush, x - 0.2f, y - 0.2f, 0.4f, 0.4f);
}
}
using (var PenP = new Pen(Color.Black, 0.1f))
using (var brush = new SolidBrush(Color.White))
{
Class1.CheckPoint();
int i = Class1.CheckPoint()[0];
int j = Class1.CheckPoint()[1];
int cp = Class1.CheckPoint()[2];
if (cp == 1)
{
PenP.Color = Color.Red;
brush.Color = Color.IndianRed;
Point[] a = { new Point(i, j), new Point(i + 1, j), new Point(i + 1, j + 1), new Point(i, j + 1) };
e.Graphics.FillPolygon(brush, a);
e.Graphics.DrawPolygon(PenP, a);
}
if (cp == 2)
{
PenP.Color = Color.Blue;
brush.Color = Color.RoyalBlue;
Point[] a = { new Point(i, j), new Point(i + 1, j), new Point(i + 1, j + 1), new Point(i, j + 1) };
e.Graphics.FillPolygon(brush, a);
e.Graphics.DrawPolygon(PenP, a);
}
}
}
//условие смены цвета под ход игрока
Color StateToColor(CellState state, byte alpha = 255)
{
var res = state == CellState.Blue ? Color.Blue : Color.Red;
return Color.FromArgb(alpha, res);
}
}

Print Preview making Issue in C#

when I click on print preview button. it shows my listed items. but when I close print preview screen and add some more items and click on print preview. it shows only that items which I enter later. I clear my old added Items.
here is my code which I'm trying
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawString("Date: " + DateTime.Now.ToShortDateString(), new Font("Calibri", 11, FontStyle.Regular), Brushes.Black, new Point(300, 150));
e.Graphics.DrawString("Customer Name: " + customername.Text.Trim(), new Font("Calibri", 11, FontStyle.Regular), Brushes.Black, new Point(20, 150));
int yPos = 200;
int xPos = 20;
int brandyPos = 180;
for (int i = numberOfItemsPrintedSoFar; i < beltlist.Count; i++)
{
numberOfItemsPerPage++;
if (numberOfItemsPerPage <= 15 && count <= 3)
{
numberOfItemsPrintedSoFar++;
if (numberOfItemsPrintedSoFar <= beltlist.Count)
{
e.Graphics.DrawString(beltlist[i].BrandName, new Font("Calibri", 11, FontStyle.Regular), Brushes.Black, new Point(xPos, brandyPos));
brandyPos = yPos + 20;
e.Graphics.DrawString(beltlist[i].BeltSize.ToString() + "--" + beltlist[i].QTY.ToString(), new Font("Calibri", 11, FontStyle.Regular), Brushes.Black, new Point(20, yPos));
yPos += 20;
}
else
{
e.HasMorePages = false;
}
}
else
{
count++;
yPos = 180;
xPos += 150;
numberOfItemsPerPage = 0;
if (count > 3)
{
e.HasMorePages = true;
xPos = 20;
count = 1;
return;
}
}
}
}

Merge RTL Datagridview columns header in C#

I want to merge 3 Datagridview columns headers (the 3rd, 4th, and the 5th
columns) and the RightToleft property of the Datagridview is enabled. i user
this code:
private void PromotionButton_Click(object sender, EventArgs e)
{
dataGridView1.ColumnHeadersHeight = dataGridView1.ColumnHeadersHeight * 2;
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.CellPainting += new DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting);
dataGridView1.Paint += new PaintEventHandler(dataGridView1_Paint);
dataGridView1.Scroll += new ScrollEventHandler(dataGridView1_Scroll);
dataGridView1.ColumnWidthChanged += new DataGridViewColumnEventHandler(dataGridView1_ColumnWidthChanged);
}
private void dataGridView1_Paint(object sender, PaintEventArgs e)
{
for (int j = 2; j < 5; j++)
{
Rectangle r1 = dataGridView1.GetCellDisplayRectangle(j, -1, true);
int w2 = dataGridView1.GetCellDisplayRectangle(j + 1, -1, true).Width;
r1.X += 1;
r1.Y += 1;
r1.Width = r1.Width + w2 - 2;
r1.Height = r1.Height / 2 - 2;
e.Graphics.FillRectangle(new SolidBrush(dataGridView1.ColumnHeadersDefaultCellStyle.BackColor), r1);
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString("رياضيات", dataGridView1.ColumnHeadersDefaultCellStyle.Font,
new SolidBrush(dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor), r1, format);
}
void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
Rectangle rtHeader = dataGridView1.DisplayRectangle;
rtHeader.Height = dataGridView1.ColumnHeadersHeight / 2;
dataGridView1.Invalidate(rtHeader);
}
void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
Rectangle rtHeader = dataGridView1.DisplayRectangle;
rtHeader.Height = dataGridView1.ColumnHeadersHeight / 2;
dataGridView1.Invalidate(rtHeader);
}
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == -1 && e.ColumnIndex > -1)
{
Rectangle r2 = e.CellBounds;
r2.Y += e.CellBounds.Height / 2;
r2.Height = e.CellBounds.Height / 2;
e.PaintBackground(r2, true);
e.PaintContent(r2);
e.Handled = true;
}
}
But the result was not like what i want, it was like this:
So how to solve this?
Assuming you want those three columns merged with only one print of the merge text, and you want to merge columns indexed 2-4:
Remove the loop.
Get the width of all three desired columns (instead of column j and j+1)
Start your Rectangle at the left-most column (column 4, not 2) since your grid has RightToLeft enabled.
private void dataGridView1_Paint(object sender, PaintEventArgs e)
{
Rectangle r1 = dataGridView1.GetCellDisplayRectangle(4, -1, true);
int w2 = dataGridView1.GetCellDisplayRectangle(3, -1, true).Width;
int w3 = dataGridView1.GetCellDisplayRectangle(2, -1, true).Width;
r1.X += 1;
r1.Y += 1;
r1.Width = r1.Width + w2 + w3;
r1.Height = r1.Height / 2 - 2;
e.Graphics.FillRectangle(new SolidBrush(dataGridView1.ColumnHeadersDefaultCellStyle.BackColor), r1);
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString("رياضيات", dataGridView1.ColumnHeadersDefaultCellStyle.Font,
new SolidBrush(dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor), r1, format);
}
Also, I would suggest using the following alignment to prevent your header text from partial obstruction:
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter;

How to block mouse inputs and simulate them programmatically?

I have a task to make a software model of device which has touchpad and screen.
I'm using C# and Windows XP.
So I have TouchpadPanel and ScreenPanel.
How can I route mouse inputs of TouchpadPanel to ScreenPanel? I want ScreenPanel (or ScreenForm) not to capture mouse and its events but to get them from TouchpadPanel. Is it really possible to do it?
I spent couple of days trying to figure out the best way to solve the problem which I described above.
Finally I found very good manner which helped me successfully finish requested job.
I decided to share with you - hopefully it might save you some time.
I used System.Windows.Forms.ControlPaint to create all the controls that I needed from scratch: buttons, labels, custom textboxes and comboboxes. Most important of all - I made separate top layer for cursor.
Now when I'm drawing everything myself I can draw extra cursor which is always visible in my window no matter what I'm doing with the real cursor.
Here is some code example:
class MCDUComboBox : MCDUStateControl
{
public event EventHandler<GosNIIAS.EventArgs<string>> SelectedIndexChanged;
private const int buttonOffset = 2;
private const int buttonWidth = 20;
private const int buttonHeight = 20;
private string[] m_items;
private int m_hightlight_index;
private int m_selected_index;
private Rectangle m_drop_down_bounds;
private int m_scroll_index;
private ButtonState m_top_scroll_button_state;
private ButtonState m_bottom_scroll_button_state;
#region Properties
public string[] Items
{
get { return m_items; }
set { m_items = value; }
}
public override string Text
{
get { return base.Text; }
set
{
if (ControlState == ControlState.Normal)
base.Text = value;
}
}
#endregion
public MCDUComboBox()
{
this.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.m_items = new string[0];
this.m_hightlight_index = -1;
this.m_selected_index = -1;
this.m_drop_down_bounds = new Rectangle();
this.m_scroll_index = 0;
this.m_top_scroll_button_state = ButtonState.Normal;
this.m_bottom_scroll_button_state = ButtonState.Normal;
}
public override void Draw(Graphics g)
{
if (Visible)
{
Rectangle bounds = ClipRectangle;
if (ControlState == ControlState.Normal)
{
g.FillRectangle(BackBrush, bounds);
g.DrawString(Text, Font, ForeBrush, bounds, StringFormat);
}
else if (ControlState == ControlState.Edit)
{
g.FillRectangle(ForeBrush, bounds);
ControlPaint.DrawBorder3D(g, bounds, Border3DStyle.Sunken);
Rectangle rectangle = new Rectangle(bounds.X + bounds.Width - buttonOffset - buttonWidth,
bounds.Y + buttonOffset,
buttonWidth,
bounds.Height - 2 * buttonOffset);
ControlPaint.DrawComboButton(g, rectangle, ButtonState.Normal);
}
else if (ControlState == ControlState.WaitingFeedback)
{
g.FillRectangle(BackBrush, bounds);
g.DrawString(Text, Font, WaitFeedbackBrush, bounds, StringFormat);
}
}
}
public override void OnMouseDown(MouseEventArgs e)
{
if (Visible)
{
Rectangle bounds = ClipRectangle;
if (bounds.Contains(e.Location))
{
if (e.Button == MouseButtons.Left)
{
if (ControlState == ControlState.Normal)
ControlState = ControlState.Edit;
}
}
else
{
if (ControlState == ControlState.Edit)
ControlState = ControlState.Normal;
}
}
}
public override bool OnMouseDownTopLayer(MouseEventArgs e)
{
if (Visible && ControlState == MCDU.Drawing.ControlState.Edit)
{
if (m_drop_down_bounds.Contains(e.Location) && m_items.Length > 0)
{
Rectangle bounds = new Rectangle(m_drop_down_bounds.X,
m_drop_down_bounds.Y,
m_items.Length > 10 ? m_drop_down_bounds.Width - buttonWidth
: m_drop_down_bounds.Width,
m_drop_down_bounds.Height);
if (bounds.Contains(e.Location))
{
if (SelectedIndexChanged != null)
{
int itemHeight = m_drop_down_bounds.Height / Math.Min(10, m_items.Length);
m_selected_index = (e.Location.Y - m_drop_down_bounds.Y) / itemHeight;
string text = m_items[m_selected_index + m_scroll_index];
SelectedIndexChanged(this, new GosNIIAS.EventArgs<string>(text));
base.Text = text;
ControlState = ControlState.WaitingFeedback;
}
else
ControlState = ControlState.Normal;
}
else
{
bounds = new Rectangle(m_drop_down_bounds.X + m_drop_down_bounds.Width - buttonWidth,
m_drop_down_bounds.Y,
buttonWidth,
buttonHeight);
if (bounds.Contains(e.Location))
{
m_scroll_index -= 1;
m_scroll_index = Math.Max(0, m_scroll_index);
m_top_scroll_button_state = ButtonState.Pushed;
}
else
{
bounds = new Rectangle(m_drop_down_bounds.X + m_drop_down_bounds.Width - buttonWidth,
m_drop_down_bounds.Y + m_drop_down_bounds.Height - buttonHeight,
buttonWidth,
buttonHeight);
if (bounds.Contains(e.Location))
{
m_scroll_index += 1;
m_scroll_index = Math.Min(m_items.Length - 10, m_scroll_index);
m_bottom_scroll_button_state = ButtonState.Pushed;
}
}
}
return true;
}
else
return false;
}
else
return false;
}
public override void OnMouseMove(MouseEventArgs e)
{
if (Visible && ControlState == MCDU.Drawing.ControlState.Edit)
{
if (m_drop_down_bounds.Contains(e.Location))
{
Rectangle bounds = new Rectangle(m_drop_down_bounds.X,
m_drop_down_bounds.Y,
m_items.Length > 10 ? m_drop_down_bounds.Width - buttonWidth
: m_drop_down_bounds.Width,
m_drop_down_bounds.Height);
if (bounds.Contains(e.Location) && m_items.Length > 0)
{
int itemHeight = m_drop_down_bounds.Height / Math.Min(10, m_items.Length);
m_hightlight_index = (e.Location.Y - m_drop_down_bounds.Y) / itemHeight + m_scroll_index;
}
}
}
}
public override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
m_top_scroll_button_state = ButtonState.Normal;
m_bottom_scroll_button_state = ButtonState.Normal;
}
public override void DrawTopLayer(Graphics g)
{
if (Visible && ControlState == MCDU.Drawing.ControlState.Edit)
{
int itemHeight = GetItemHeight(g);
Rectangle bounds = ClipRectangle;
m_drop_down_bounds = new Rectangle(bounds.X,
bounds.Y + bounds.Height,
bounds.Width,
itemHeight * Math.Max(1, Math.Min(10, m_items.Length)) + 2);
g.FillRectangle(ForeBrush, m_drop_down_bounds);
g.DrawRectangle(new Pen(BackColor), new Rectangle(m_drop_down_bounds.X,
m_drop_down_bounds.Y,
m_drop_down_bounds.Width - 1,
m_drop_down_bounds.Height - 1));
for (int index = 0; index < Math.Min(10, m_items.Length); index++)
{
Rectangle itemBounds = new Rectangle(bounds.X,
bounds.Y + bounds.Height + index * itemHeight,
m_items.Length > 10 ? bounds.Width - buttonWidth : bounds.Width,
itemHeight);
if (m_hightlight_index == index + m_scroll_index)
g.FillRectangle(new SolidBrush(SystemColors.Highlight), itemBounds);
g.DrawString(m_items[index + m_scroll_index], Font, BackBrush, itemBounds, StringFormat);
}
if (m_items.Length > 10)
{
Rectangle rectangle = new Rectangle(m_drop_down_bounds.X + m_drop_down_bounds.Width - buttonWidth - 1,
m_drop_down_bounds.Y + 1,
buttonWidth,
itemHeight * 10);
g.FillRectangle(new SolidBrush(SystemColors.ScrollBar), rectangle);
rectangle = new Rectangle(m_drop_down_bounds.X + m_drop_down_bounds.Width - buttonWidth - 1,
m_drop_down_bounds.Y + 1,
buttonWidth,
buttonHeight);
ControlPaint.DrawScrollButton(g, rectangle, ScrollButton.Up, m_top_scroll_button_state);
rectangle = new Rectangle(m_drop_down_bounds.X + m_drop_down_bounds.Width - buttonWidth - 1,
m_drop_down_bounds.Y + 1 + itemHeight * 10 - buttonHeight,
buttonWidth,
buttonHeight);
ControlPaint.DrawScrollButton(g, rectangle, ScrollButton.Down, m_bottom_scroll_button_state);
int height = (int)((itemHeight * 10 - 2 * buttonHeight) * 10.0 / m_items.Length);
int y = m_drop_down_bounds.Y + 1 + buttonHeight +
(int)((itemHeight * 10 - 2 * buttonHeight) * m_scroll_index / m_items.Length);
rectangle = new Rectangle(m_drop_down_bounds.X + m_drop_down_bounds.Width - buttonWidth - 1,
y,
buttonWidth,
height);
ControlPaint.DrawButton(g, rectangle, ButtonState.Normal);
}
}
}
protected int GetItemHeight(Graphics g)
{
return (int)g.MeasureString(" ", Font).Height;
}
}

paint rectangle on column header in c#

I have painted the datagridview column header and called the repaint event in the scroll event ,but it does not seems to repaint properly . The text in the painted rectangle gets scettered ( see the second image)
here is my code,
void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
Rectangle rtHeader = this.dataGridView1.DisplayRectangle;
rtHeader.Y += 0;
rtHeader.Height = this.dataGridView1.ColumnHeadersHeight;
}
Rectangle r1;
void dataGridView1_Paint(object sender, PaintEventArgs e)
{
string[] monthes = { "APPLE", "MANGO", "CHERRY", "GRAPES", "PINEAPPLE" };
for (int j = 0; j < this.dataGridView1.ColumnCount; )
{
r1 = this.dataGridView1.GetCellDisplayRectangle(j, -1, true);
int w2 = this.dataGridView1.GetCellDisplayRectangle(j + 1, -1, true).Width;
r1.X += -2;
r1.Y += 30;
r1.Width = r1.Width + w2 - 1;
r1.Height = r1.Height / 3 - 2;
e.Graphics.FillRectangle(new SolidBrush(this.dataGridView1.ColumnHeadersDefaultCellStyle.BackColor), r1);
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
e.Graphics.DrawRectangle(new Pen(Color.Black), r1);
e.Graphics.DrawString(monthes[j / 2], this.dataGridView1.ColumnHeadersDefaultCellStyle.Font, new SolidBrush(this.dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor), r1, format);
j += 2;
}
string[] year = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY" };
//for (int i = 0; i < this.dataGridView1.ColumnCount; )
//{
Rectangle rec = this.dataGridView1.GetCellDisplayRectangle(0, -1, true);
int wid = this.dataGridView1.GetCellDisplayRectangle(1, -1, true).Width;
rec.X += -2;
rec.Y += 1;
rec.Width = this.dataGridView1.Columns.GetColumnsWidth(DataGridViewElementStates.Visible);
rec.Height = rec.Height / 3 - 2;
e.Graphics.FillRectangle(new SolidBrush(this.dataGridView1.ColumnHeadersDefaultCellStyle.BackColor), rec);
StringFormat frm = new StringFormat();
frm.Alignment = StringAlignment.Center;
frm.LineAlignment = StringAlignment.Center;
e.Graphics.DrawRectangle(new Pen(Color.Black), rec);
e.Graphics.DrawString("Favourite fruits", new Font("Times new roman", 16, FontStyle.Regular), new SolidBrush(Color.CornflowerBlue), rec, frm);
}
private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
/*
Rectangle rtHeader = this.dataGridView1.DisplayRectangle;
rtHeader.Y += 0;
rtHeader.Height = this.dataGridView1.ColumnHeadersHeight;
this.dataGridView1.Invalidate(rtHeader);
*/
this.dataGridView1.Invalidate();
}
if (e.RowIndex == -1 && e.ColumnIndex > -1)
{
e.PaintBackground(e.CellBounds, true);
RenderColumnHeader(e.Graphics, e.CellBounds, e.CellBounds.Contains(hotSpot) ? hotSpotColor : backColor);
RenderColumnHeaderBorder(e.Graphics, e.CellBounds, e.ColumnIndex);
using (Brush brush = new SolidBrush(e.CellStyle.ForeColor))
{
using (StringFormat sf = new StringFormat() { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center })
{
e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, brush, e.CellBounds, sf);
}
}
e.Handled = true;
}
}
Color hotSpotColor = Color.LightGreen;//For hover backcolor
Color backColor = Color.MediumSeaGreen; //For backColor
Point hotSpot;
private void RenderColumnHeader(Graphics g, Rectangle headerBounds, Color c)
{
int topHeight = 10;
Rectangle topRect = new Rectangle(headerBounds.Left, headerBounds.Top + 1, headerBounds.Width, topHeight);
RectangleF bottomRect = new RectangleF(headerBounds.Left, headerBounds.Top + 1 + topHeight, headerBounds.Width, headerBounds.Height - topHeight - 4);
Color c1 = Color.FromArgb(180, c);
using (SolidBrush brush = new SolidBrush(c1))
{
g.FillRectangle(brush, topRect);
brush.Color = c;
g.FillRectangle(brush, bottomRect);
}
}
private void RenderColumnHeaderBorder(Graphics g, Rectangle headerBounds, int colIndex)
{
ControlPaint.DrawBorder3D(g, headerBounds, Border3DStyle.Raised, Border3DSide.All & ~Border3DSide.Middle);
}
//MouseMove event handler for your dataGridView1
private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
hotSpot = e.Location;
}
//MouseLeave event handler for your dataGridView1
private void dataGridView1_MouseLeave(object sender, EventArgs e)
{
hotSpot = Point.Empty;
}

Categories

Resources