I'm writing a custom control for WPF (a drawn one) and I'm having massive performance issues. The fact is that I'm drawing a lots of text and this might be a part of the problem. I timed the OnRender method however, and I'm faced with very weird results - the whole method (especially after moving to GlyphRun implemenation) takes around 2-3ms to complete. Everything looks like following (take a look at the Output window for debug timing results) (requires Flash to play):
https://www.screencast.com/t/5p6mC6rxFv0
The OnRender method doesn't have anything special in particular, it just renders some rectangles and text:
protected override void OnRender(DrawingContext drawingContext)
{
var stopwatch = Stopwatch.StartNew();
ValidateMetrics();
base.OnRender(drawingContext);
var pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip;
// Draw header
DrawHeader(drawingContext, pixelsPerDip);
// Draw margin
DrawMargin(drawingContext, pixelsPerDip);
// Draw data
DrawData(drawingContext, pixelsPerDip);
// Draw footer
DrawFooter(drawingContext);
stopwatch.Stop();
System.Diagnostics.Debug.WriteLine($"Drawing took {stopwatch.ElapsedMilliseconds}ms");
}
I ran Visual Studio's performance analysis and got the following results:
Clearly "Layout" of the editor control takes a lot of time, but still rendering is very quick.
How to debug this performance issue further? Why performance is so low despite OnRender taking milliseconds to run?
Edit - as response to comments
I didn't find a good way to time drawing, though I found, what was the cause of the problem and it turned out to be text drawing. I ended up with using very low-level text drawing mechanism, using GlyphRuns and it turned out to be fast enough to display full HD worth of text at least 30 frames per second, what was enough for me.
I'll post some relevant pieces of code below. Please note though: this is not ready-to-use solution, but should point anyone interested in the right direction.
private class GlyphRunInfo
{
public GlyphRunInfo()
{
CurrentPosition = 0;
}
public void FillMissingAdvanceWidths()
{
while (AdvanceWidths.Count < GlyphIndexes.Count)
AdvanceWidths.Add(0);
}
public List<ushort> GlyphIndexes { get; } = new List<ushort>();
public List<double> AdvanceWidths { get; } = new List<double>();
public double CurrentPosition { get; set; }
public double? StartPosition { get; set; }
}
// (...)
private void BuildTypeface()
{
typeface = new Typeface(FontFamily);
if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
{
typeface = null;
glyphTypeface = null;
}
}
private void AddGlyph(char c, double position, GlyphRunInfo info)
{
if (glyphTypeface.CharacterToGlyphMap.TryGetValue(c, out ushort glyphIndex))
{
info.GlyphIndexes.Add(glyphIndex);
if (info.GlyphIndexes.Count > 1)
info.AdvanceWidths.Add(position - info.CurrentPosition);
info.CurrentPosition = position;
if (info.StartPosition == null)
info.StartPosition = info.CurrentPosition;
}
}
private void DrawGlyphRun(DrawingContext drawingContext, GlyphRunInfo regularRun, Brush brush, double y, double pixelsPerDip)
{
if (regularRun.StartPosition != null)
{
var glyphRun = new GlyphRun(glyphTypeface,
bidiLevel: 0,
isSideways: false,
renderingEmSize: FontSize,
pixelsPerDip: (float)pixelsPerDip,
glyphIndices: regularRun.GlyphIndexes,
baselineOrigin: new Point(Math.Round(regularRun.StartPosition.Value),
Math.Round(glyphTypeface.Baseline * FontSize + y)),
advanceWidths: regularRun.AdvanceWidths,
glyphOffsets: null,
characters: null,
deviceFontName: null,
clusterMap: null,
caretStops: null,
language: null);
drawingContext.DrawGlyphRun(brush, glyphRun);
}
}
And then some random code, which used the prior methods:
var regularRun = new GlyphRunInfo();
var selectionRun = new GlyphRunInfo();
// (...)
for (int ch = 0, index = line * Document.BytesPerRow; ch < charPositions.Count && index < availableBytes; ch++, index++)
{
byte drawnByte = dataBuffer[index];
char drawnChar = (drawnByte < 32 || drawnByte > 126) ? '.' : (char)drawnByte;
if (enteringMode == EnteringMode.Overwrite && (selection?.IsCharSelected(index + offset) ?? false))
AddGlyph(drawnChar, charPositions[ch].Position.TextCharX, selectionRun);
else
AddGlyph(drawnChar, charPositions[ch].Position.TextCharX, regularRun);
}
regularRun.FillMissingAdvanceWidths();
selectionRun.FillMissingAdvanceWidths();
DrawGlyphRun(drawingContext, regularRun, SystemColors.WindowTextBrush, linePositions[line].TextStartY, pixelsPerDip);
DrawGlyphRun(drawingContext, selectionRun, SystemColors.HighlightTextBrush, linePositions[line].TextStartY, pixelsPerDip);
Related
I would like to cut the extra text and display three dots(...) and when user clicks on the cell, everthing has to be displayed. how to calculate the width of the property grid cell and cut the text. Any help will be grateful.
Pictures are attached for explanation
Instead of this
I would like to achieve this
and it should vary according to the cell size
The property grid does not allow that and you cannot customize it to do so using any official way.
However, here is some sample code that seems to work. It uses a TypeConverter to reduce the value from the grid's size.
Use at your own risk as it relies on PropertyGrid's internal methods and may have an impact on performance, since it requires a refresh on the whole grid on each resize.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// note this may have an impact on performance
propertyGrid1.SizeChanged += (sender, e) => propertyGrid1.Refresh();
var t = new Test();
t.MyStringProperty = "The quick brown fox jumps over the lazy dog";
propertyGrid1.SelectedObject = t;
}
}
public class AutoSizeConverter : TypeConverter
{
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value == null)
return null;
// small trick to get PropertyGrid control (view) from context
var view = (Control)context.GetService(typeof(IWindowsFormsEditorService));
// bigger trick (hack) to get value column width & font
int width = (int)view.GetType().GetMethod("GetValueWidth").Invoke(view, null);
var font = (Font)view.GetType().GetMethod("GetBoldFont").Invoke(view, null); // or GetBaseFont
// note: the loop is not super elegant and may probably be improved in terms of performance using some of the other TextRenderer overloads
string s = value.ToString();
string ellipsis = s;
do
{
var size = TextRenderer.MeasureText(ellipsis, font);
if (size.Width < width)
return ellipsis;
s = s.Substring(0, s.Length - 1);
ellipsis = s + "...";
}
while (true);
}
}
public class Test
{
// we use a custom type converter
[TypeConverter(typeof(AutoSizeConverter))]
public string MyStringProperty { get; set; }
}
Here is the result (supports resize):
I've been attempting to use PNG images as textures in Unity, when I use only one or two its easy to drag and drop them in the inspector. In my current project I have over 300 images which I am trying to load into an array, I then want to change the texture each time round the update so it appears like a video.
Here is what I have so far:
using UnityEngine;
using System.Collections;
public class ChangeImage : MonoBehaviour {
public Texture[] frames;
public int CurrentFrame;
public object[] images;
void OnMouseDown() {
if (GlobalVar.PlayClip == false){
GlobalVar.PlayClip = true;
} else {
GlobalVar.PlayClip = false;
}
}
public void Start() {
images = Resources.LoadAll("Frames");
for (int i = 0; i < images.Length; i++){
Texture2D texImage = (Texture2D) images[i];
frames[i] = texImage;
}
}
// Update is called once per frame
void Update () {
if(GlobalVar.PlayClip == true){
CurrentFrame++;
CurrentFrame %= frames.Length;
GetComponent<Renderer>().material.mainTexture = frames[CurrentFrame];
}
}
}
I have been attempting to load the images into an object array convert them to textures then output to a texture array. Does anyone know where I am going wrong with this it does not seem to give any errors but the texture is not changing?
Any advice is much appreciated
Thanks
What you are doing is kinda slow and inappropriate.
What I would recommend is to use the Animator and an animation. Have all your textures into a atlas texture, this way you will limit the draw call amount. Make that texture a sprite and use the sprite editor to cut in sub sprite.
Add an animator and create an animation. Select the whole sub sprites and drag them into the animation. Done.
Now you can easily control the speed and the playing via the animator component.
I managed to fix the problem eventually, the problem seemed to be the loading of assets was not working correctly and this was why the frame was not changing. I also changed the name of the folder containing the images from "Frames" to "Resources". Here is the completed code for anyone else who needs it:
using UnityEngine;
using System.Collections;
public class ChangeImage : MonoBehaviour {
public Texture[] frames;
public int CurrentFrame;
void OnMouseDown() {
if (GlobalVar.PlayClip == false){
GlobalVar.PlayClip = true;
} else {
GlobalVar.PlayClip = false;
}
}
public void Start() {
frames = Resources.LoadAll<Texture>("");
}
// Update is called once per frame
void Update () {
if(GlobalVar.PlayClip == true){
CurrentFrame %= frames.Length;
CurrentFrame++;
Debug.Log ("Current Frame is " + CurrentFrame);
GetComponent<Renderer>().material.mainTexture = frames[CurrentFrame];
}
}
}
Thanks for the advice on animations I will still look into it as the performance of the images is not great.
I am trying to create sort of a radar. Radar is VisualCollection that consists of 360 DrawingVisual's (which represent radar beams). Radar is placed on Viewbox.
class Radar : FrameworkElement
{
private VisualCollection visuals;
private Beam[] beams = new Beam[BEAM_POSITIONS_AMOUNT]; // all geometry calculation goes here
public Radar()
{
visuals = new VisualCollection(this);
for (int beamIndex = 0; beamIndex < BEAM_POSITIONS_AMOUNT; beamIndex++)
{
DrawingVisual dv = new DrawingVisual();
visuals.Add(dv);
using (DrawingContext dc = dv.RenderOpen())
{
dc.DrawGeometry(Brushes.Black, null, beams[beamIndex].Geometry);
}
}
DrawingVisual line = new DrawingVisual();
visuals.Add(line);
// DISCRETES_AMOUNT is about 500
this.Width = DISCRETES_AMOUNT * 2;
this.Height = DISCRETES_AMOUNT * 2;
}
public void Draw(int beamIndex, Brush brush)
{
using (DrawingContext dc = ((DrawingVisual)visuals[beamIndex]).RenderOpen())
{
dc.DrawGeometry(brush, null, beams[beamIndex].Geometry);
}
}
protected override Visual GetVisualChild(int index)
{
return visuals[index];
}
protected override int VisualChildrenCount
{
get { return visuals.Count; }
}
}
Each DrawingVisual has precalculated geometry for DrawingContext.DrawGeometry(brush, pen, geometry). Pen is null and brush is a LinearGradientBrush with about 500 GradientStops. The brush gets updated every few milliseconds, lets say 16 ms for this example. And that is what gets laggy. Here goes the overall logic.
In MainWindow() constructor I create the radar and start a background thread:
private Radar radar;
public MainWindow()
{
InitializeComponent();
radar = new Radar();
viewbox.Child = radar;
Thread t = new Thread(new ThreadStart(Run));
t.Start();
}
In Run() method there is an infinite loop, where random brush is generated, Dispatcher.Invoke() is called and a delay for 16 ms is set:
private int beamIndex = 0;
private Random r = new Random();
private const int turnsPerMinute = 20;
private static long delay = 60 / turnsPerMinute * 1000 / (360 / 2);
private long deltaDelay = delay;
public void Run()
{
int beginTime = Environment.TickCount;
while (true)
{
GradientStopCollection gsc = new GradientStopCollection(DISCRETES_AMOUNT);
for (int i = 1; i < Settings.DISCRETES_AMOUNT + 1; i++)
{
byte color = (byte)r.Next(255);
gsc.Add(new GradientStop(Color.FromArgb(255, 0, color, 0), (double)i / (double)DISCRETES_AMOUNT));
}
LinearGradientBrush lgb = new LinearGradientBrush(gsc);
lgb.StartPoint = Beam.GradientStarts[beamIndex];
lgb.EndPoint = Beam.GradientStops[beamIndex];
lgb.Freeze();
viewbox.Dispatcher.Invoke(new Action( () =>
{
radar.Draw(beamIndex, lgb);
}));
beamIndex++;
if (beamIndex >= BEAM_POSITIONS_AMOUNT)
{
beamIndex = 0;
}
while (Environment.TickCount - beginTime < delay) { }
delay += deltaDelay;
}
}
Every Invoke() call it performs one simple thing: dc.DrawGeometry(), which redraws the beam under current beamIndex. However, sometimes it seems, like before UI updates, radar.Draw() is called few times and instead of drawing 1 beam per 16 ms, it draws 2-4 beams per 32-64 ms. And it is disturbing. I really want to achieve smooth movement. I need one beam to get drawn per exact period of time. Not this random stuff. This is the list of what I have tried so far (nothing helped):
placing radar in Canvas;
using Task, BackgroundWorker, Timer, custom Microtimer.dll and setting different Thread Priorities;
using different ways of implementing delay: Environment.TickCount, DateTime.Now.Ticks, Stopwatch.ElapsedMilliseconds;
changing LinearGradientBrush to predefined SolidColorBrush;
using BeginInvoke() instead of Invoke() and changing Dispatcher Priorities;
using InvalidateVisuals() and ugly DoEvents();
using BitmapCache, WriteableBitmap and RenderTargetBitmap (using DrawingContext.DrawImage(bitmap);
working with 360 Polygon objects instead of 360 DrawingVisuals. This way I could avoid using Invoke() method. Polygon.FillProperty of each polygon was bound to ObservableCollection, and INotifyPropertyChanged was implemented. So simple line of code {brushCollection[beamIndex] = (new created and frozen brush)} led to polygon FillProperty update and UI was getting redrawn. But still no smooth movement;
probably there were few more little workarounds I could forget about.
What I did not try:
use tools to draw 3D (Viewport) to draw 2D radar;
...
So, this is it. I am begging for help.
EDIT: These lags are not about PC resources - without delay radar can do about 5 full circles per second (moving pretty fast). Most likely it is something about multithread/UI/Dispatcher or something else that I am yet to understand.
EDIT2: Attaching an .exe file so you could see what is actually going on: https://dl.dropboxusercontent.com/u/8761356/Radar.exe
EDIT3: DispatcherTimer(DispatcherPriority.Render) did not help aswell.
For smooth WPF animations you should make use of the
CompositionTarget.Rendering event.
No need for a thread or messing with the dispatcher. The event will automatically be fired before each new frame, similar to HTML's requestAnimationFrame().
In the event update your WPF scene and you're done!
There is a complete example available on MSDN.
You can check some graphics bottleneck using the WPF Performance Suite:
http://msdn.microsoft.com/es-es/library/aa969767(v=vs.110).aspx
Perforator is the tool that will show you performance issues. Maybe you are using a low performance VGA card?
while (Environment.TickCount - beginTime < delay) { }
delay += deltaDelay;
The sequence above blocks the thread. Use instead "await Task.Delay(...)" which doesn't block the thread like its counterpart Thread.Sleep(...).
I use WPF. My app has some textblocks with changeable text inside. Each one has width of 200 and height of 150. The problem is that I have 7 textblocks like those and I want them to have the same font size. The text must be autofitted. I know that can autofit them up. But when one has a sentence inside and another only two words, the font size is so different... I need to recount size asynchronically (e.g. creating some event like OnTextChange). Text inside blocks changes dynamically. How to write a function? I want to pass 3 parameters: text, font (font family + font style) and textblock size, and return fitted font size.
The best way to determine the appropriate font size is to measure the text at any arbitrary size, and then multiply it by the ratio of its size to the size of the area.
For example, if you measure the text and it is half of the size of the container it's in, you can multiply it by 2 and it should fill the container. You want to choose the minimum of either the width or height ratio to use.
In WPF the FormattedText class does text measuring.
public double GetFontSize(string text, Size availableSize, Typeface typeFace)
{
FormattedText formtxt = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeFace, 10, Brushes.Black);
double ratio = Math.Min(availableSize.Width / formtxt.Width, availableSize.Height / formtxt.Height);
return 10 * ratio;
}
You would use this function whenever you change the text of your TextBlocks, like so:
txtBlock.FontSize = GetFontSize(txt.Text, new Size(txt.ActualWidth, txt.ActualHeight), new Typeface(txt.FontFamily, txt.FontStyle, txt.FontWeight, txt.FontStretch));
Edit:
For the purposes of practicality, you might want to be able to have the text to center vertically in this predefined bounding rectangle. A good way to do that is to wrap your TextBlock inside another object such as a Border element. This way you can tell your TextBlock to align in the center of the border and it can auto-size to fit its content.
Ok. Works fine. But I've got another problem. I wrote 2 methods in MainWindow.cs:
private void fitFontSize()
{
propertiesList.Clear();
TextUtils.FontProperty fontProps = new TextUtils.FontProperty();
foreach (TextBlock tb in findVisualChildren<TextBlock>(statusOptionsGrid))
{
fontProps.Text = tb.Text;
fontProps.Size = new Size(tb.ActualWidth, tb.ActualHeight);
fontProps.FontFamily = tb.FontFamily;
fontProps.FontStyle = tb.FontStyle;
fontProps.FontWeight = tb.FontWeight;
fontProps.FontStretch = tb.FontStretch;
propertiesList.Add(fontProps);
}
MessageBox.Show(TextUtils.recalculateFontSize(propertiesList) + "");
}
public IEnumerable<T> findVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in findVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
After that I created a new class for text processing. Here's the code:
public class TextUtils
{
public class FontProperty
{
public FontFamily FontFamily { get; set; }
public FontStyle FontStyle { get; set; }
public FontWeight FontWeight { get; set; }
public FontStretch FontStretch { get; set; }
public string Text { get; set; }
public Size Size { get; set; }
public Typeface getTypeFace()
{
return new Typeface(FontFamily, FontStyle, FontWeight, FontStretch);
}
}
public static double recalculateFontSize(List<FontProperty> propertiesList)
{
List<double> fontSizes = new List<double>();
foreach (FontProperty fp in propertiesList)
{
fontSizes.Add(getFontSizeForControl(fp));
}
return fontSizes.Min<double>();
}
private static double getFontSizeForControl(FontProperty fp)
{
string text = fp.Text;
Size availableSize = fp.Size;
Typeface typeFace = fp.getTypeFace();
FormattedText formtxt = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeFace, 10, Brushes.Black);
double ratio = Math.Min(availableSize.Width / formtxt.Width, availableSize.Height / formtxt.Height);
return 10 * ratio;
}
}
The code looks bad but I will correct it later...
Ok. Now I want to create a new timer which checks font sizes every second. When I try to use fitFontSize() method in it, I get the msg: "The calling thread cannot access this object because a different thread owns it."
How to do this in order to avoid problems like that?
I tried (just a try) creating new thread calling this method. But there is the same problem with findVisualChildren<>() method - it's called in fitFontSize(). I don't have any ideas how to solve my problem...
Our company is developing an application (WPF, targeted to .NET 3.5) with the WPF Diagramming Components from MindFusion.Apparently, printing and saving XPS Documents results in various errors on different systems.
I reduced the problem to a single sample XPS Document created from our application.I'll first give an overview of the concerned systems and break down the issues when respectively saving an xps document and printing the diagram visual using the new WPF Printing Path in the following list:
Note: All three systems have Windows XP SP3 with .NET 3.5 Framework SP1 installed.
Using the XpsDocumentWriter to write a XPS document with the Paginator:
PC 1 - The XPS Viewer (working with IE 7.0) doesn’t work (even after reinstall of .Net 3.5). XPS Viewer from the Essential Pack opens the document, but the view is completely blurred. But as you can see, our application on the right side of the screenshot uses a DocumentViewer to test this issue, which works correctly. Printing from the corrupted XPS Viewer results in the same output as on screen, while printing from the integrated print function in the DocumentViewer ( without intervention from our application) gives a blurry output which is a little more readable, but still not acceptable.
PC 2 - The IE XPS Viewer works correctly. The print ouput is inconsistent. Sometimes, the graphics (Shapes) are not complete, or the printing device notifies about lack of memory (with the same document).
PC 3 – The IE XPS Viewer works correctly, but initiating a print job always leads to this exception within IE itself.
Note: All heretofore mentioned issues have been tested with the XPS Document (already mentioned above) created by our application.
Creating a print job with PrintDialog.PrintDocument and the Paginator:
Printing from our application gives a consistent output with all system: the bigger the document (speaking in term of the page media size), the more blurry it gets. Unfortunately, a lot of potential causes have been already omitted.
The code for printing the document is fairly simple.
• Instead of using our own Paginator, I replaced the latter with another Paginator part of the MindFusion WPF Diagraming Components we use. I achieved the same result. (This statement is also true for XPSDocuments saved as file).
• I used the latest print driver available
• Changes to PrintTicket Resolution doesn’t seem to affect the ouput in any way
• Using another Visual instead of a diagram (like the Window of our Application itself) doesn’t affect the output
Due to these various issues, it seems that multiple causes are also probable. The previous exclusions lead me to assume that some crucial settings are missing in the PrintTicket, or something terribly wrong happens with the XPS to GDI Conversion behnd scenes. Apart from these assumptions, I'm running out of ideas.
Note: All print devices have non-XPS Drivers. HP Designjet 500, HP 2100
Last but not least, I serialised the same PrintTicket used for XPS Document file and the print job.
I would be thankful if anybody has experienced similar issues. Any suggestion is welcome.
I have currently working code but I am still having alignment issues. But print is not blurred I am giving you my code in hope that it may help you and we both could find a solution.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Windows;
using System.Windows.Media;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Controls;
using System.Data;
namespace VD
{
public class CustomPaginator : DocumentPaginator
{
private int _RowsPerPage;
private Size _PageSize;
private int _Rows;
public static DataTable dtToPrint;
public CustomPaginator()
{
}
public CustomPaginator(int rows, Size pageSize, DataTable dt)
{
_Rows = rows;
PageSize = pageSize;
dtToPrint = dt;
}
public override DocumentPage GetPage(int pageNumber)
{
int currentRow = _RowsPerPage * pageNumber;
var page = new PageElement(currentRow, Math.Min(_RowsPerPage, _Rows - currentRow))
{
Width = PageSize.Width,
Height = PageSize.Height,
};
page.Measure(PageSize);
page.Arrange(new Rect(new Point(0,0), PageSize));
return new DocumentPage(page);
}
public override bool IsPageCountValid
{ get { return true; } }
public override int PageCount
{ get { return (int)Math.Ceiling(_Rows / (double)_RowsPerPage); } }
public DataTable getDtProtols
{
get
{
return dtToPrint;
}
}
public override Size PageSize
{
get { return _PageSize; }
set
{
_PageSize = value;
_RowsPerPage = PageElement.RowsPerPage(PageSize.Height);
//Can't print anything if you can't fit a row on a page
Debug.Assert(_RowsPerPage > 0);
}
}
public override IDocumentPaginatorSource Source
{ get { return null; } }
}
public class PageElement : UserControl
{
private const int PageMargin = 75;
private const int HeaderHeight = 25;
private const int LineHeight = 20;
private const int ColumnWidth = 140;
private CustomPaginator objParent = new CustomPaginator();
private DataTable ProtocolsDT = null;
private int _CurrentRow;
private int _Rows;
public PageElement(int currentRow, int rows)
{
Margin = new Thickness(PageMargin);
_CurrentRow = currentRow;
_Rows = rows;
}
private static FormattedText MakeText(string text)
{
return new FormattedText(text, CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface("Tahoma"), 14, Brushes.Black);
}
public static int RowsPerPage(double height)
{
return (int)Math.Floor((height - (2 * PageMargin)
- HeaderHeight) / LineHeight);
}
protected override void OnRender(DrawingContext dc)
{
ProtocolsDT = objParent.getDtProtols;
Point curPoint = new Point(0, 0);
dc.DrawText(MakeText("Host Names"),curPoint );
curPoint.X += ColumnWidth;
for (int i = 1; i < ProtocolsDT.Columns.Count; i++)
{
dc.DrawText(MakeText(ProtocolsDT.Columns[i].ToString()), curPoint);
curPoint.X += ColumnWidth;
}
curPoint.X = 0;
curPoint.Y += LineHeight;
dc.DrawRectangle(Brushes.Black, null, new Rect(curPoint, new Size(Width, 2)));
curPoint.Y += HeaderHeight - LineHeight;
Random numberGen = new Random();
//for (int i = _CurrentRow; i < _CurrentRow + _Rows; i++)
//{
// dc.DrawText(MakeText(ProtocolsDT.Rows[i][0].ToString()), curPoint);
//curPoint.X += ColumnWidth;
for (int j = 0; j < ProtocolsDT.Rows.Count; j++)
{
for (int z = 0; z < ProtocolsDT.Rows[j].ItemArray.Length; z++)
{
dc.DrawText(MakeText(ProtocolsDT.Rows[j].ItemArray[z].ToString()), curPoint);
curPoint.X += ColumnWidth;
}
curPoint.Y += LineHeight;
curPoint.X = 0;
//dc.DrawText(MakeText(ProtocolsDT.Rows[j].ItemArray[1].ToString()), curPoint);
//curPoint.X += ColumnWidth;
//dc.DrawText(MakeText(ProtocolsDT.Rows[j].ItemArray[2].ToString()), curPoint);
//curPoint.X += ColumnWidth;
//}
//curPoint.Y += LineHeight;
//curPoint.X = 0;
}
}
}
}
Another Class
private void PrintDataTable(DataTable dt)
{
var printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
var paginator = new CustomPaginator(dt.Rows.Count,
new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight),dt);
try
{
printDialog.PrintDocument(paginator, "Running Protocols Report");
}
catch (Exception ex)
{
MessageBox.Show(this, "Unable to print protocol information. Please check your printer settings.", "VD", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
}
}
}