WPF Adding Image as Content to Button doesn't work - c#

I am trying to create image 15-puzzle game, where you have to combine the image by sliding the squares.
Almost everything works correctly, except that instead of showing the image inside a button it shows it as a text "System.Drawing.Image".
Here is my MainWindow.xaml.cs code:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Collections;
using static System.Math;
using System.Collections.Generic;
using System.Drawing;
using Image = System.Drawing.Image;
using Brushes = System.Windows.Media.Brushes;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace Quizz
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//Array of buttons
private static readonly List<Button> Buttons = new List<Button>(15);
// Position of an empty space
private static int _xPos;
private static int _yPos;
public MainWindow()
{
InitializeComponent();
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
for (var i = 0; i < 15; i++)
{
Buttons.Add(new Button() { Background = Brushes.AliceBlue });
}
_xPos = new Random(int.Parse(Guid.NewGuid().ToString().Substring(0, 8), System.Globalization.NumberStyles.HexNumber)).Next(3);
_yPos = new Random(int.Parse(Guid.NewGuid().ToString().Substring(0, 8), System.Globalization.NumberStyles.HexNumber)).Next(3);
CreateDynamicWpfGrid();
}
private void CreateDynamicWpfGrid()
{
// Create the Grid
var dynamicGrid = new Grid { ShowGridLines = true };
// Create Columns
var gridCol1 = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) };
var gridCol2 = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) };
var gridCol3 = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) };
var gridCol4 = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) };
dynamicGrid.ColumnDefinitions.Add(gridCol1);
dynamicGrid.ColumnDefinitions.Add(gridCol2);
dynamicGrid.ColumnDefinitions.Add(gridCol3);
dynamicGrid.ColumnDefinitions.Add(gridCol4);
// Create Rows
var gridRow1 = new RowDefinition { Height = new GridLength(1, GridUnitType.Star) };
var gridRow2 = new RowDefinition { Height = new GridLength(1, GridUnitType.Star) };
var gridRow3 = new RowDefinition { Height = new GridLength(1, GridUnitType.Star) };
var gridRow4 = new RowDefinition { Height = new GridLength(1, GridUnitType.Star) };
dynamicGrid.RowDefinitions.Add(gridRow1);
dynamicGrid.RowDefinitions.Add(gridRow2);
dynamicGrid.RowDefinitions.Add(gridRow3);
dynamicGrid.RowDefinitions.Add(gridRow4);
// Bind Buttons and Grid Cells
int j = 0;
var imgList = Randomizer();
for (var i = 0; i < 16; i++)
{
if (i % 4 != _xPos || _yPos != i / 4)
{
//Add image in a button
Buttons[j].Content = imgList[j];
Buttons[j].Click += Button_Click;
Grid.SetColumn(Buttons[j], i%4);
Grid.SetRow(Buttons[j], i/4);
dynamicGrid.Children.Add(Buttons[j]);
j++;
}
}
// Display grid into a Window
RootWindow.Content = dynamicGrid;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var button = (Button)sender;
var x = Grid.GetColumn(button);
var y = Grid.GetRow(button);
if ((Abs(_xPos - x) != 1 || Abs(_yPos - y) != 0) && (Abs(_yPos - y) != 1 || Abs(_xPos - x) != 0)) return;
Grid.SetColumn(button, _xPos);
Grid.SetRow(button, _yPos);
_xPos = x;
_yPos = y;
}
private List<Image> Randomizer()
{
var imageList = CropImage();
var randomImageList = new List<Image>(15);
for (var i = 0; i < 15; i++)
{
var pos = new Random(int.Parse(Guid.NewGuid().ToString().Substring(0, 8), System.Globalization.NumberStyles.HexNumber)).Next(imageList.Count);
randomImageList.Add(imageList[pos]);
imageList.RemoveAt(pos);
}
return randomImageList;
}
private Bitmap ResizeImage(Image image)
{
var destRect = new Rectangle(0, 0, (int)RootWindow.Width ,(int) RootWindow.Height );
var destImage = new Bitmap((int)RootWindow.Width, (int)RootWindow.Height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
private List<Image> CropImage()
{
var imgList = new List<Image>(16);
var img = (Image)ResizeImage(Image.FromFile(#"D:\Documents\Шаг\Программы WPF\Quizz\Quizz\Resources\Image.jpeg"));
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
var index = i * 4 + j;
imgList.Add(new Bitmap(80, 80));
var graphics = Graphics.FromImage(imgList[index]);
graphics.DrawImage(img, new Rectangle(0, 0, 80, 80), new Rectangle(i * 80, j * 80, 80, 80), GraphicsUnit.Pixel);
graphics.Dispose();
}
}
imgList.RemoveAt(imgList.Count - 1);
return imgList;
}
}
}
Here is my MainWindow.xaml code:
<Window x:Class="Quizz.MainWindow"
Title="Пятнашки" Icon="pack://application:,,,/Quizz;component/resources/Icon.ico"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="320" Width="320"
Name="RootWindow" ResizeMode="NoResize"
Loaded="MainWindow_Loaded">
</Window>
What am I doing wrong??

Here is what I did to get this to work.
I created a list of StackPanels similar to your button list.
private static readonly List<StackPanel> StackPanels = new List<StackPanel>(15);
then populated the list like you did the buttons..
private static readonly List<StackPanel> StackPanels = new List<StackPanel>(15);
Then Here is the for loop with the fix in the CreateDynamicWPFGrid method. Added the Stack panel to the content and added the Image to the stack panel after converting it to a Control.Image.
// Bind Buttons and Grid Cells
int j = 0;
var imgList = Randomizer();
for (var i = 0; i < 16; i++)
{
if (i % 4 != _xPos || _yPos != i / 4)
{
//Add image in a button
var bitmapImage = new BitmapImage();
var bitmap = imgList[j];
using (var memoryStream = new MemoryStream())
{
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
}
var image = new System.Windows.Controls.Image
{
Source = bitmapImage,
Stretch = Stretch.None
};
var currentstack = StackPanels[j];
currentstack.Orientation = Orientation.Horizontal;
currentstack.Children.Add(image);
Buttons[j].Content = currentstack;
Buttons[j].Click += Button_Click;
Grid.SetColumn(Buttons[j], i % 4);
Grid.SetRow(Buttons[j], i / 4);
dynamicGrid.Children.Add(Buttons[j]);
j++;
}
}

Related

Object not shown on Canvas (WPF Application)

In this Application, i have a car class with a method called Spawn (which should draw the object on a Canvas which i defined in the XAML file). I call the Method in MainWindow, but when I run my program, there is no car being drawn onto the Canvas.
Here is the Spawn method:
public void Spawn(Canvas cvs)
{
cvs = new Canvas();
cvs.Children.Clear();
carBody.Width = 70;
carBody.Height = 120;
carBody.Background = new SolidColorBrush(Color);
Canvas.SetLeft(carBody, SpawnLocation.X);
Canvas.SetTop(carBody, SpawnLocation.Y);
Rectangle[] tires = new Rectangle[4];
Rectangle[] windows = new Rectangle[2];
Label lblBrand = new Label();
RotateTransform rotation = new RotateTransform();
// Reifen
tires[0] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[0], -9);
Canvas.SetTop(tires[0], 18);
tires[1] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[1], 61);
Canvas.SetTop(tires[1], 18);
tires[2] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[2], -9);
Canvas.SetTop(tires[2], 80);
tires[3] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[3], 61);
Canvas.SetTop(tires[3], 80);
// Fenster
windows[0] = new Rectangle() // Front
{
Fill = Brushes.White,
Width = 50,
Height = 40
};
Canvas.SetLeft(windows[0], 0);
Canvas.SetTop(windows[0], 0);
windows[1] = new Rectangle() // rear
{
Fill = Brushes.White,
Width = 50,
Height = 50
};
Canvas.SetLeft(windows[1], 0);
Canvas.SetTop(windows[1], 0);
// Label Automarke
lblBrand.Width = 40;
lblBrand.Height = 23;
lblBrand.Content = Brand;
// Add2Canvas
for (int i = 0; i < tires.Length; i++)
carBody.Children.Add(tires[i]);
for (int i = 0; i < windows.Length; i++)
carBody.Children.Add(windows[i]);
carBody.Children.Add(lblBrand);
if (Direction == "nord")
{
rotation.Angle = 0;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
else if (Direction == "süd")
{
rotation.Angle = 180;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
else if (Direction == "west")
{
rotation.Angle = 90;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
else if (Direction == "ost")
{
rotation.Angle = 270;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
cvs.Children.Add(carBody);
}
Calling the methodMainWindow:
Car car1;
public MainWindow()
{
InitializeComponent();
car1 = new Car("Audi", Colors.Red);
car1.Direction = "west";
car1.SpawnLocation = new Point(550, 340);
car1.Spawn(gameScreen);
}
Thanks in advance!
Fixed it! I initialized the argmument of my Spawn method, it now works after I deleted it.
My method looked like this first:
public void Spawn(Canvas cvs)
{
cvs = new Canvas();
cvs.Children.Clear();
carBody.Width = 70;
I initialized my the Argument, but since i don't wanna create a new Canvas, i deleted these two first lines of my method.
public void Spawn(Canvas cvs)
{
carBody.Width = 70;
carBody.Height = 120;
carBody.Background = new SolidColorBrush(Color);
Now its working fine.

How to print C# chart with more pages

I have C# project already done but im having issue with printing it's charts when comes out with more pages of data points, i got the scroll bar work when start getting more pages so the user can review all data on all pages but i could not find how to make the print preview shows them or print them,
when click on print, it shows only the first page on the print preview and same thing when print it out.
her is the print code:
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document = this.chart1.Printing.PrintDocument;
((Form)ppd).WindowState = FormWindowState.Maximized;
chart1.Printing.PrintDocument.DefaultPageSettings.Landscape = true;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Left = 0;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Right = 0;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Top = 0;
chart1.Printing.PrintDocument.DefaultPageSettings.Margins.Bottom = 0;
ppd.ShowDialog();
and here is the chart load code:
public void loadChart(string sqlvalue)//load chart method
{
chart1.ChartAreas[0].AxisY.Maximum = 55;
chart1.ChartAreas[0].AxisY.Minimum = 35;
chart1.ChartAreas[0].AxisY.Interval = 5;//control how many lines/Interval
chart1.ChartAreas[0].AxisY.ScrollBar.Enabled = true;
chart1.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
chart1.ChartAreas[0].AxisX.Minimum = 0;
// chart1.ChartAreas[0].AxisX.Maximum = 10;
chart1.ChartAreas[0].AxisX.Interval = 1;
//X AXES label angle
chart1.ChartAreas[0].AxisX.LabelStyle.Angle = 60;
da = new SqlDataAdapter(sqlvalue, cn.connect());
da.Fill(dt);
this.chart1.DataSource = dt;
this.chart1.Series["left"].XValueMember = dt.Columns[3].ToString();//date data
this.chart1.Series["left"].YValueMembers = dt.Columns[1].ToString();//spindle 1 data
this.chart1.Series["Right"].YValueMembers = dt.Columns[2].ToString();//spindle 2 data
//label the series lines, Backcolor and forcolor
chart1.Series[0].LabelBackColor = Color.Red;
chart1.Series[0].LabelForeColor = Color.White;
//datapoint marker's color, bordercolor,style and size
chart1.Series[0].MarkerColor = Color.White;
chart1.Series[0].MarkerBorderColor = Color.Black;
chart1.Series[0].MarkerStyle = MarkerStyle.Circle;
chart1.Series[0].MarkerSize = 8;
//datapoint marker's color, style and size
chart1.Series[1].MarkerColor = Color.White;
chart1.Series[1].MarkerBorderColor = Color.Black;
chart1.Series[1].MarkerStyle = MarkerStyle.Circle;
chart1.Series[1].MarkerSize = 8;
chart1.Series[1].LabelBackColor = Color.Blue;
chart1.Series[1].LabelForeColor = Color.White;
//Chart background lines color
chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.Silver;
chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.Silver;
this.chart1.DataBind();
cn.disconnect();
// enable autoscroll
chart1.ChartAreas[0].CursorX.AutoScroll = true;//------------
chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
chart1.ChartAreas[0].AxisX.ScaleView.Zoom(0, 15);
chart1.ChartAreas[0].AxisX.ScrollBar.ButtonStyle = ScrollBarButtonStyles.SmallScroll;
// set scrollbar small change to the target size
chart1.ChartAreas[0].AxisX.ScaleView.SmallScrollSize = 15;
Legend left = new Legend();
Legend LC = CustomCloneLegend(chart1, left);
chart1.Legends.Add(LC);
chart1.Padding = Padding.Empty;
ChartArea CA = chart1.ChartAreas[0];
CA.Position = new ElementPosition(4,6, 100, 90);
}
Thank you for your time and help, here is the chart code update:
private static Image MergeImages(List<Image> imageList)
{
var finalSize = new Size();
foreach (var image in imageList)
{
if (image.Width > finalSize.Width)
{
finalSize.Width = image.Width;
}
finalSize.Height += image.Height;
}
var outputImage = new Bitmap(finalSize.Width, finalSize.Height);
using (var gfx = Graphics.FromImage(outputImage))
{
var y = 0;
foreach (var image in imageList)
{
gfx.DrawImage(image, 0, y);
y += image.Height;
}
}
return outputImage;
}
The second method:
List<Image> ChartsToImages(List<Chart> charts)
{
var imageList = new List<Image>();
foreach (var c in charts)
{
using (var ms = new MemoryStream())
{
c.SaveImage(ms, ChartImageFormat.Png);
var bmp = System.Drawing.Bitmap.FromStream(ms);
imageList.Add(bmp);
}
}
return imageList;
}
and this code
var chartList = new List<Chart> { chart1 };
var imageList = ChartsToImages(chartList);
var finalImage = MergeImages(imageList);
finalImage.Save("D:\\Junk.png", ImageFormat.Png);
Im not sure is that what you mean by your first comment, but i found this code here under Converting chart to image questions. this code convert and saves the chart in the same amount of pages but i need to show them in the printpreviewcontrol and print them.
Below code refers to the as per page count starting point and ending point based printing. And Grid view value chars are row loop based counting the page.
private int numberOfItemsPerPage = 0;
private int numberOfItemsPrintedSoFar = 0;
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int height = 480; //page height stating point
for (int l = numberOfItemsPrintedSoFar; l < dataGridView2.Rows.Count; l++)
{
numberOfItemsPerPage = numberOfItemsPerPage + 1;
if (numberOfItemsPerPage <= 25) // 25 is Page Line Item
{
numberOfItemsPrintedSoFar++;
if (numberOfItemsPrintedSoFar <= dataGridView2.Rows.Count)
{
height += dataGridView2.Rows[0].Height;
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[0].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(5, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[1].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(170, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[2].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(290, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
e.Graphics.DrawString(dataGridView2.Rows[l].Cells[3].FormattedValue.ToString(), dataGridView2.Font = new Font("Book Antiqua", 8), Brushes.Black, new RectangleF(345, height, dataGridView2.Columns[0].Width, dataGridView2.Rows[0].Height));
}
else
{
e.HasMorePages = false;
}
}
else
{
numberOfItemsPerPage = 0;
e.HasMorePages = true;
return;
}
}
numberOfItemsPerPage = 0;
numberOfItemsPrintedSoFar = 0;
}

Print all data in the DataGrid in WPF

I am working on WPF application. I have data in the DataGrid which I have to print all the data present in it. I tried like this...
publicMainWindow()
{
InitializeComponent();
DataTabledt = newDataTable();
dt.Columns.Add("S.No");
dt.Columns.Add("Name");
dt.Columns.Add("Father's Name");
dt.Columns.Add("D-O-B");
dt.Columns.Add("Qualification");
dt.Columns.Add("Gender");
dt.Columns.Add("SSC %");
dt.Columns.Add("+2 %");
dt.Columns.Add("Graduation %");
dt.Columns.Add("Work Experience");
dt.Columns.Add("Company");
object[] rowValues = {"01","Gopi","Ravi","31","Degree","M", "88","85", "80","2 Years","Blah Blah"};
dt.Rows.Add(rowValues);
dt.AcceptChanges();
myGrid.DataContext = dt.DefaultView;
}
privatevoidPrint_Click(object sender, RoutedEventArgs e)
{
PrintDialogprintDlg = newPrintDialog();
if ((bool)printDlg.ShowDialog().GetValueOrDefault())
{
Sizepagesize = newSize(printDlg.PrintableAreaWidth,printDlg.PrintableAreaHeight);
myGrid.Measure(pagesize);
myGrid.Arrange(newRect(5, 5, pagesize.Width, pagesize.Height));
printDlg.PrintVisual(myGrid, "Personal Information");
}
}
when I click on print button it is printing only the data which we can see as below
But in my case it is not printing work experience and company columns. How can I Print all the fields. Please help me out
EDIT: I think FlowDocument is used, but suppose I have 50 rows I cannot use FlowDocument. How can I Print in this case.
I have done code recently. It is tested code.It will print every datagrid with all records.It is easy and simple code.You would add a class. If you want to decorate a datagrid then go to PrintDG class then decorate it according to your own requirement.
Follow these steps.
Step1: Add these references on top.
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
public class PrintDG
{
public void printDG(DataGrid dataGrid, string title)
{
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
FlowDocument fd = new FlowDocument();
Paragraph p = new Paragraph(new Run(title));
p.FontStyle = dataGrid.FontStyle;
p.FontFamily = dataGrid.FontFamily;
p.FontSize = 18;
fd.Blocks.Add(p);
Table table = new Table();
TableRowGroup tableRowGroup = new TableRowGroup();
TableRow r = new TableRow();
fd.PageWidth = printDialog.PrintableAreaWidth;
fd.PageHeight = printDialog.PrintableAreaHeight;
fd.BringIntoView();
fd.TextAlignment = TextAlignment.Center;
fd.ColumnWidth = 500;
table.CellSpacing = 0;
var headerList = dataGrid.Columns.Select(e => e.Header.ToString()).ToList();
List<dynamic> bindList = new List<dynamic>();
for (int j = 0; j < headerList.Count; j++)
{
r.Cells.Add(new TableCell(new Paragraph(new Run(headerList[j]))));
r.Cells[j].ColumnSpan = 4;
r.Cells[j].Padding = new Thickness(4);
r.Cells[j].BorderBrush = Brushes.Black;
r.Cells[j].FontWeight = FontWeights.Bold;
r.Cells[j].Background = Brushes.DarkGray;
r.Cells[j].Foreground = Brushes.White;
r.Cells[j].BorderThickness = new Thickness(1, 1, 1, 1);
var binding = (dataGrid.Columns[j] as DataGridBoundColumn).Binding as Binding;
bindList.Add(binding.Path.Path);
}
tableRowGroup.Rows.Add(r);
table.RowGroups.Add(tableRowGroup);
for (int i = 0; i < dataGrid.Items.Count; i++)
{
dynamic row;
if (dataGrid.ItemsSource.ToString().ToLower() == "system.data.linqdataview")
{ row = (DataRowView)dataGrid.Items.GetItemAt(i); }
else
{
row = (BalanceClient)dataGrid.Items.GetItemAt(i);
}
table.BorderBrush = Brushes.Gray;
table.BorderThickness = new Thickness(1, 1, 0, 0);
table.FontStyle = dataGrid.FontStyle;
table.FontFamily = dataGrid.FontFamily;
table.FontSize = 13;
tableRowGroup = new TableRowGroup();
r = new TableRow();
for (int j = 0; j < row.Row.ItemArray.Count(); j++)
{
if (dataGrid.ItemsSource.ToString().ToLower() == "system.data.linqdataview")
{
r.Cells.Add(new TableCell(new Paragraph(new Run(row.Row.ItemArray[j].ToString()))));
}
else
{
r.Cells.Add(new TableCell(new Paragraph(new Run(row.GetType().GetProperty(bindList[j]).GetValue(row, null)))));
}
r.Cells[j].ColumnSpan = 4;
r.Cells[j].Padding = new Thickness(4);
r.Cells[j].BorderBrush = Brushes.DarkGray;
r.Cells[j].BorderThickness = new Thickness(0, 0, 1, 1);
}
tableRowGroup.Rows.Add(r);
table.RowGroups.Add(tableRowGroup);
}
fd.Blocks.Add(table);
printDialog.PrintDocument(((IDocumentPaginatorSource)fd).DocumentPaginator, "");
}
}
}
Step2: Then go to print button click event and create object of PrintDG class then call printDG pass to It two parameters datagridname and title.
Like :
private void print_button_Click(object sender, RoutedEventArgs e)
{
PrintDG print = new PrintDG();
print.printDG(datagridName, "Title");
}
If any error occurs during execution tell me and I will solve It.This is running code only, you need copy and paste.
Edited:
I declared row as dynamic. The dynamic keyword decides at run time which type to instantiate, either DataTable or another.
I work with This :
// Author : Kadi Okba
public class WpfPrinting
{
public const double cm = 37;
public double Margin = 0.5 * cm;
public double PageWidth = 21 * cm;
public double PageHeight = 29 * cm;
public double RowHeight = 0.7 * cm;
public bool PageNumberVisibility = true;
public bool DateVisibility = true;
public double FontSize = 14;
public double HeaderFontSize = 14;
public bool IsBold = false;
public void PrintDataGrid(FrameworkElement header, DataGrid grid, FrameworkElement footer, PrintDialog printDialog)
{
if (header == null) { header = new FrameworkElement(); header.Width = 1; header.Height = 1; }
if (footer == null) { footer = new FrameworkElement(); footer.Width = 1; footer.Height = 1; }
if (grid == null) return;
Size pageSize = new Size(PageWidth, PageHeight);
FixedDocument fixedDoc = new FixedDocument();
fixedDoc.DocumentPaginator.PageSize = pageSize;
double GridActualWidth = grid.ActualWidth == 0 ? grid.Width : grid.ActualWidth;
double PageWidthWithMargin = pageSize.Width - Margin * 2;
double PageHeightWithMargin = pageSize.Height - Margin * 2;
// scale the header
double headerScale = (header?.Width ?? 0) / PageWidthWithMargin;
double headerWidth = PageWidthWithMargin;
double headerHeight = (header?.Height ?? 0) * headerScale;
header.Height = headerHeight;
header.Width = headerWidth;
// scale the footer
double footerScale = (footer?.Width ?? 0) / PageWidthWithMargin;
double footerWidth = PageWidthWithMargin;
double footerHeight = (footer?.Height ?? 0) * footerScale;
footer.Height = footerHeight;
footer.Width = footerWidth;
int pageNumber = 1;
string Now = DateTime.Now.ToShortDateString();
//add the header
FixedPage fixedPage = new FixedPage();
fixedPage.Background = Brushes.White;
fixedPage.Width = pageSize.Width;
fixedPage.Height = pageSize.Height;
FixedPage.SetTop(header, Margin);
FixedPage.SetLeft(header, Margin);
fixedPage.Children.Add(header);
// its like cursor for current page Height to start add grid rows
double CurrentPageHeight = headerHeight + 1 * cm;
int lastRowIndex = 0;
bool IsFooterAdded = false;
for (;;)
{
int AvaliableRowNumber;
var SpaceNeededForRestRows = (CurrentPageHeight + (grid.Items.Count - lastRowIndex) * RowHeight);
//To avoid printing the footer in a separate page
if (SpaceNeededForRestRows > (pageSize.Height - footerHeight - Margin) && (SpaceNeededForRestRows < (pageSize.Height - Margin)))
AvaliableRowNumber = (int)((pageSize.Height - CurrentPageHeight - Margin - footerHeight) / RowHeight);
// calc the Avaliable Row acording to CurrentPageHeight
else AvaliableRowNumber = (int)((pageSize.Height - CurrentPageHeight - Margin) / RowHeight);
// create new page except first page cause we created it prev
if (pageNumber > 1)
{
fixedPage = new FixedPage();
fixedPage.Background = Brushes.White;
fixedPage.Width = pageSize.Width;
fixedPage.Height = pageSize.Height;
}
// create new data grid with columns width and binding
DataGrid gridToAdd;
gridToAdd = GetDataGrid(grid, GridActualWidth, PageWidthWithMargin);
FixedPage.SetTop(gridToAdd, CurrentPageHeight); // top margin
FixedPage.SetLeft(gridToAdd, Margin); // left margin
// add the avaliable rows to the cuurent grid
for (int i = lastRowIndex; i < grid.Items.Count && i < AvaliableRowNumber + lastRowIndex; i++)
{
gridToAdd.Items.Add(grid.Items[i]);
}
lastRowIndex += gridToAdd.Items.Count + 1;
// add date
TextBlock dateText = new TextBlock();
if (DateVisibility) dateText.Visibility = Visibility.Visible;
else dateText.Visibility = Visibility.Hidden;
dateText.Text = Now;
// add page number
TextBlock PageNumberText = new TextBlock();
if (PageNumberVisibility) PageNumberText.Visibility = Visibility.Visible;
else PageNumberText.Visibility = Visibility.Hidden;
PageNumberText.Text = "Page : " + pageNumber;
FixedPage.SetTop(dateText, PageHeightWithMargin);
FixedPage.SetLeft(dateText, Margin);
FixedPage.SetTop(PageNumberText, PageHeightWithMargin);
FixedPage.SetLeft(PageNumberText, PageWidthWithMargin - PageNumberText.Text.Length * 10);
fixedPage.Children.Add(gridToAdd);
fixedPage.Children.Add(dateText);
fixedPage.Children.Add(PageNumberText);
// calc Current Page Height to know the rest Height of this page
CurrentPageHeight += gridToAdd.Items.Count * RowHeight;
// all grid rows added
if (lastRowIndex >= grid.Items.Count)
{
// if footer have space it will be added to the same page
if (footerHeight < (PageHeightWithMargin - CurrentPageHeight))
{
FixedPage.SetTop(footer, CurrentPageHeight + Margin);
FixedPage.SetLeft(footer, Margin);
fixedPage.Children.Add(footer);
IsFooterAdded = true;
}
}
fixedPage.Measure(pageSize);
fixedPage.Arrange(new Rect(new Point(), pageSize));
fixedPage.UpdateLayout();
PageContent pageContent = new PageContent();
((IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
pageNumber++;
// go to start position : New page Top
CurrentPageHeight = Margin;
// this mean that lastRowIndex >= grid.Items.Count and the footer dont have enough space
if (lastRowIndex >= grid.Items.Count && !IsFooterAdded)
{
FixedPage ffixedPage = new FixedPage();
ffixedPage.Background = Brushes.White;
ffixedPage.Width = pageSize.Width;
ffixedPage.Height = pageSize.Height;
FixedPage.SetTop(footer, Margin);
FixedPage.SetLeft(footer, Margin);
TextBlock fdateText = new TextBlock();
if (DateVisibility) fdateText.Visibility = Visibility.Visible;
else fdateText.Visibility = Visibility.Hidden;
dateText.Text = Now;
TextBlock fPageNumberText = new TextBlock();
if (PageNumberVisibility) fPageNumberText.Visibility = Visibility.Visible;
else fPageNumberText.Visibility = Visibility.Hidden;
fPageNumberText.Text = "Page : " + pageNumber;
FixedPage.SetTop(fdateText, PageHeightWithMargin);
FixedPage.SetLeft(fdateText, Margin);
FixedPage.SetTop(fPageNumberText, PageHeightWithMargin);
FixedPage.SetLeft(fPageNumberText, PageWidthWithMargin - PageNumberText.ActualWidth);
ffixedPage.Children.Add(footer);
ffixedPage.Children.Add(fdateText);
ffixedPage.Children.Add(fPageNumberText);
ffixedPage.Measure(pageSize);
ffixedPage.Arrange(new Rect(new Point(), pageSize));
ffixedPage.UpdateLayout();
PageContent fpageContent = new PageContent();
((IAddChild)fpageContent).AddChild(ffixedPage);
fixedDoc.Pages.Add(fpageContent);
IsFooterAdded = true;
}
if (IsFooterAdded)
{
break;
}
}
PrintFixedDocument(fixedDoc, printDialog);
}
private DataGrid GetDataGrid(DataGrid grid, double GridActualWidth, double PageWidthWithMargin)
{
DataGrid printed = new DataGrid();
// styling the grid
Style rowStyle = new Style(typeof(DataGridRow));
rowStyle.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.White));
rowStyle.Setters.Add(new Setter(Control.FontSizeProperty, FontSize));
if (IsBold) rowStyle.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.Bold));
rowStyle.Setters.Add(new Setter(Control.HeightProperty, RowHeight));
Style columnStyle = new Style(typeof(DataGridColumnHeader));
columnStyle.Setters.Add(new Setter(Control.FontSizeProperty, HeaderFontSize));
columnStyle.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Center));
columnStyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0, 0.5, 0, 1.5)));
columnStyle.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.White));
columnStyle.Setters.Add(new Setter(Control.BorderBrushProperty, Brushes.Black));
columnStyle.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.SemiBold));
printed.RowStyle = rowStyle;
printed.VerticalGridLinesBrush = Brushes.Black;
printed.HorizontalGridLinesBrush = Brushes.Black;
printed.FontFamily = new FontFamily("Arial");
printed.RowBackground = Brushes.White;
printed.Background = Brushes.White;
printed.Foreground = Brushes.Black;
// get the columns of grid
foreach (var column in grid.Columns)
{
if (column.Visibility != Visibility.Visible) continue;
DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.HeaderStyle = columnStyle;
textColumn.Header = column.Header;
textColumn.Width = column.ActualWidth / GridActualWidth * PageWidthWithMargin;
textColumn.Binding = ((DataGridTextColumn)column).Binding;
printed.Columns.Add(textColumn);
}
printed.BorderBrush = Brushes.Black;
return printed;
}
public void PrintFixedDocument(FixedDocument fixedDoc, PrintDialog printDialog)
{
XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printDialog.PrintQueue);
writer.Write(fixedDoc, printDialog.PrintTicket);
}
}

Graphics graphics = Graphics.FromImage(BitMap_1); // <--This is not allowed? How

Graphics graphics = Graphics.FromImage(BitMap_1); // <--This is not allowed? How can I fix it?How can I declare graphics as global?
Here is some more code...
Here is some more code...
Here is some more code...
Here is some more code...
public partial class Form1 : Form
{
string WAV_filePath = #"";
string MIDI_filePath = #"";
string filePath = #"C:\Users\Steffan\Desktop\guitar\Gert toets die Elektroniese Konsertina.wav";//Guitar 2.wav";//Sine Wave 440Hz.wav";
SoundPlayer player1 = new SoundPlayer();
byte[] RawWaveDataArray = new byte[100];
Int16[] Data_16Bit = new Int16[100];
int NumberOfSamples = 0;
bool PLAY_ = false;
Point[] Points = new Point[886];
// Create pen.
Pen Pen_ = new Pen(Color.White, 0);
Bitmap BitMap_1 = new Bitmap(1138, 72);
Graphics graphics = Graphics.FromImage(BitMap_1); // <--This is not allowed? How can I fix it?How can I declare graphics as global?
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (PLAY_ == true)
{
Wave_x_Inc = 0;
graphics.Clear(Color.Black);
for (int x = 0; x < 886; x++)
{
Points[x] = new Point(Wave_x_Inc, (int)((Data_16Bit[DataIndex] * 0.002F) + (pictureBox4.Height / 2)));
Wave_x_Inc = Wave_x_Inc + 2;
DataIndex = DataIndex + 2;
if (DataIndex > Data_16Bit.Length/2) { DataIndex = 0; x = 886; }
}
if (Wave_x_Inc > pictureBox4.Width) { Wave_x_Inc = 0; }
graphics.DrawBeziers(Pen_, Points);
WaveLengthCounter = WaveLengthCounter + 886;
int Temp_Val = WaveLengthCounter / DataLenth_Fraction;
if (Temp_Val <= 300) { trackBar1.Value = Temp_Val; }
else { trackBar1.Value = 0; }
if (WaveLengthCounter > Data_16Bit.Length/2)
{
WaveLengthCounter = 0;
}
pictureBox4.Image = BitMap_1;
}
}
}
Try this, it may help you.
var bitmap = new Bitmap(width, height);
var graphics = Graphics.FromImage(bitmap);
graphics.DrawRectangle(Pens.Black, 0, 0, 10, 10);
bitmap.Save("MyShapes.png");

How to customize message box

I am doing C# application, and I want to change the style of a message box. Is it possible or not?
Example: change button style, fore color, etc.
You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:
FormBorderStyle FixedToolWindow
ShowInTaskBar False
StartPosition CenterScreen
To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:
MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
// etc
}
It would be advisable to add your own Show method that takes the text and other options you require:
public DialogResult Show(string text, Color foreColour)
{
lblText.Text = text;
lblText.ForeColor = foreColour;
return this.ShowDialog();
}
MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
Here is the code needed to create your own message box:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyStuff
{
public class MyLabel : Label
{
public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
{
Label l = new Label();
l.Text = Text;
l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
l.AutoSize = true;
return l;
}
}
public class MyButton : Button
{
public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
{
Button b = new Button();
b.Text = Text;
b.Width = Width;
b.Height = Height;
b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
return b;
}
}
public class MyImage : PictureBox
{
public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
{
PictureBox i = new PictureBox();
if (ImagePath != null)
{
i.BackgroundImageLayout = ImageLayout.Zoom;
i.Location = new Point(9, 9);
i.Margin = new Padding(3, 3, 2, 3);
i.Size = new Size(Width, Height);
i.TabStop = false;
i.Visible = true;
i.BackgroundImage = Image.FromFile(ImagePath);
}
else
{
i.Visible = true;
i.Size = new Size(0, 0);
}
return i;
}
}
public partial class MyMessageBox : Form
{
private MyMessageBox()
{
this.panText = new FlowLayoutPanel();
this.panButtons = new FlowLayoutPanel();
this.SuspendLayout();
//
// panText
//
this.panText.Parent = this;
this.panText.AutoScroll = true;
this.panText.AutoSize = true;
this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
//this.panText.Location = new Point(90, 90);
this.panText.Margin = new Padding(0);
this.panText.MaximumSize = new Size(500, 300);
this.panText.MinimumSize = new Size(108, 50);
this.panText.Size = new Size(108, 50);
//
// panButtons
//
this.panButtons.AutoSize = true;
this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.panButtons.FlowDirection = FlowDirection.RightToLeft;
this.panButtons.Location = new Point(89, 89);
this.panButtons.Margin = new Padding(0);
this.panButtons.MaximumSize = new Size(580, 150);
this.panButtons.MinimumSize = new Size(108, 0);
this.panButtons.Size = new Size(108, 35);
//
// MyMessageBox
//
this.AutoScaleDimensions = new SizeF(8F, 19F);
this.AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new Size(206, 133);
this.Controls.Add(this.panButtons);
this.Controls.Add(this.panText);
this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.Margin = new Padding(4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new Size(168, 132);
this.Name = "MyMessageBox";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.CenterScreen;
this.ResumeLayout(false);
this.PerformLayout();
}
public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
List<Label> Labels = new List<Label>();
Labels.Add(Label);
return Show(Labels, Title, Buttons, Image);
}
public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
List<Label> Labels = new List<Label>();
Labels.Add(MyLabel.Set(Label));
return Show(Labels, Title, Buttons, Image);
}
public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
if (Labels == null) Labels = new List<Label>();
if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
if (Buttons == null) Buttons = new List<Button>();
if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
List<Button> buttons = new List<Button>(Buttons);
buttons.Reverse();
int ImageWidth = 0;
int ImageHeight = 0;
int LabelWidth = 0;
int LabelHeight = 0;
int ButtonWidth = 0;
int ButtonHeight = 0;
int TotalWidth = 0;
int TotalHeight = 0;
MyMessageBox mb = new MyMessageBox();
mb.Text = Title;
//Image
if (Image != null)
{
mb.Controls.Add(Image);
Image.MaximumSize = new Size(150, 300);
ImageWidth = Image.Width + Image.Margin.Horizontal;
ImageHeight = Image.Height + Image.Margin.Vertical;
}
//Labels
List<int> il = new List<int>();
mb.panText.Location = new Point(9 + ImageWidth, 9);
foreach (Label l in Labels)
{
mb.panText.Controls.Add(l);
l.Location = new Point(200, 50);
l.MaximumSize = new Size(480, 2000);
il.Add(l.Width);
}
int mw = Labels.Max(x => x.Width);
il.ToString();
Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
mb.panText.Height = Labels.Sum(l => l.Height);
mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
LabelWidth = mb.panText.Width;
LabelHeight = mb.panText.Height;
//Buttons
foreach (Button b in buttons)
{
mb.panButtons.Controls.Add(b);
b.Location = new Point(3, 3);
b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
b.Click += new EventHandler(mb.Button_Click);
}
ButtonWidth = mb.panButtons.Width;
ButtonHeight = mb.panButtons.Height;
//Set Widths
if (ButtonWidth > ImageWidth + LabelWidth)
{
Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
mb.panText.Height = Labels.Sum(l => l.Height);
mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
LabelWidth = mb.panText.Width;
LabelHeight = mb.panText.Height;
}
TotalWidth = ImageWidth + LabelWidth;
//Set Height
TotalHeight = LabelHeight + ButtonHeight;
mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);
mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
mb.ShowDialog();
return mb.Result;
}
private FlowLayoutPanel panText;
private FlowLayoutPanel panButtons;
private int ScrollBarWidth(List<Label> Labels)
{
return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
}
private void Button_Click(object sender, EventArgs e)
{
Result = ((Button)sender).Text;
Close();
}
private string Result = "";
}
}

Categories

Resources