It appears you get the value from the textbox and put it into mylocalstring
within the printDocument1_ PrintPage routine, but you never reset the textbox
to what is left. This means, the textbox remains the same throughout the
printing and thus there is always more than one page left to print.
"raylopez99 " <ra********@yah oo.comwrote in message
news:b4******** *************** ***********@z66 g2000hsc.google groups.com...
On Aug 28, 5:57 am, Family Tree Mike
<FamilyTreeM... @discussions.mi crosoft.comwrot e:
No kidding FTM! Printing is indeed very complicated in .NET. In
fact, I'm giving up after this post! (assuming I don't get a reply
that fixes the below)
I just spent half a day doing various things trying to get print to
work. I finally got it to work--somewhat--but with one big caveat--
the print only prints one page! If it's more than one page of text,
you get an infinite loop (the pages just keep increasing, until you
hit cancel).
Below is the code, and where I think the infinite loop problem is--
I've keyword marked it with 'fooey' (see also // Infinite Loop? Why?)
Like I say, everything works fine, if the textbox has one page of text
in it or less.
I also tried setting up a temporary file and writing and reading from
it, but it's the same as reading from a textbox (but nevertheless I
left this code in below, commented out).
I appreciate you guys helping. Please don't spend too much time on
this--I've thrown in the towel--but I do believe the problem is in the
place marked "fooey" below--you are not 'consuming' your string
properly when using the method ".Substring " (this code was from an
example on the net--see the header)--and thus the string never
'decreases' so you always get a "e.HasMoreP ages = true;" condition,
rather than "= false".
If any of you pity a newbie, please upload a working example of a
simple print (no preview required) for printing from a textbox.
RL
//adapted from
http://www.expresscomputeronline.com...hspace02.shtml
//main code from here
// an excellent example, too bad it doesn't work for me
// and from Chris Sells, Chapter 8, Printing in WinForms
//Chris Sells Chap 8 is very very simplistic--in retrospect I suspect
because printing is difficult and he didn't want to spend time on it
//
using System;
using System.Collecti ons.Generic;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows. Forms;
using System.Diagnost ics;
using System.Drawing. Printing; //needed for print
namespace MyProgram1
{
public partial class MyPrintForm : Form
{
string myPrintFilename ;
StringBuilder myGlobalStringB uilder;
Font f;
SolidBrush b;
StringFormat strformat;
string printstr;
int intchars, intlines;
StreamReader reader;
public MyPrintForm()
{
InitializeCompo nent();
myGlobalStringB uilder = new StringBuilder() ;
strformat = new StringFormat();
FileNotSavedYet = true; //dirty file bool indicator—not
used
}
private void printToolStripB utton_Click(obj ect sender,
EventArgs e)
{
if (myPrintFilenam e != "")
{
this.printDocum ent1.DocumentNa me =
this.myPrintFil ename;
this.printDocum ent1.Print();
}
}
private void printDocument1_ PrintPage(objec t sender,
System.Drawing. Printing.PrintP ageEventArgs e)
{
////try writing textbox text to a file first! Make it
write to a temp file and read back.
////// //UPDATE: Not true,you still get an infinite loop
if you do this
//string path1 =
System.IO.Path. GetDirectoryNam e(System.Reflec tion.Assembly.G etExecutingAsse mbly().Location );
//string path2 = "\\temp12345432 1.txt"; //temporary file
name
//string path12 = path1 + path2; //local path + file name
//try
//{
// using (FileStream fs = new FileStream(path 12,
FileMode.Create )) //fs = new FileStream("tes t123454321.txt" ,
FileMode.OpenOr Create)
// {
// using (StreamWriter myWritter = new
StreamWriter(fs , System.Text.Enc oding.ASCII))
// {
// myWritter.Write (textBox1.Text) ;
// }
// }
//}
//catch(Exception ex)
//{
// MessageBox.Show (ex.Message);
//}
//string mylocalstring;
//try
//{
// reader = new StreamReader(pa th12);
//}
//catch (Exception ex)
//{
// MessageBox.Show ("reader err:" + ex.Message);
//}
//mylocalstring = reader.ReadToEn d();
RectangleF myrect = new
RectangleF(e.Ma rginBounds.Left ,e.MarginBounds .Top,
e.MarginBounds. Width,e.MarginB ounds.Height);
SizeF sz = new SizeF(e.MarginB ounds.Width,
e.MarginBounds. Height);
string mylocalstring = textBox1.Text; //also equivalent it
turns out--same thing!
//thus, no need to create and save a temporary file from the textBox1—
just use directly.
//mylocalstring = myGlobalStringB uilder.ToString ();
e.Graphics.Meas ureString(myloc alstring, f, sz, strformat,
out intchars, out intlines);
printstr = mylocalstring.S ubstring(0,intc hars);
e.Graphics.Draw String(printstr , f, b, myrect,strforma t);
if (mylocalstring. Length intchars)
{
mylocalstring = mylocalstring.S ubstring(intcha rs);//
problem here! fooey!
// Infinite Loop? Why?
// one idea: is mylocalstring being changed? note .Substring library
method here has only one parameter
//should .Substring method not have two parameters?
// Update: tried with ‘mylocalstring =
mylocalstring.S ubstring(0,intc hars); and still failed
// but, perhaps the first parameter should be intchar + intchar*N,
where N=0,1,2? Anybody have thoughts?
e.HasMorePages = true;
}
else
e.HasMorePages = false;
//end of relevant code--rest below is not relevant to this problem --
RL
////p. 292 Chris Sells
////draw to the e.Graphics object that wraps the print
target
//Graphics g = e.Graphics;
//using (Font font = new Font("Courier", 12))
//{
// string mylocalstring;
// // mylocalstring =
myGlobalStringB uilder.ToString (); //commented out, an earlier version
used this
// mylocalstring = textBox1.Text;
// if (myGlobalString Builder.Length != 0)
// {
// g.DrawString(my localstring, font, Brushes.Blue,
0, 0);
// }
//}
////// end of pg. 292 Chris Sells
}
// this is code that you need to open a file. Not really relevant for
the 'infinite loop' problem above, but I include for Pavel
private void openAToolStripB uttun_Click(obj ect sender,
EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog( );
openFileDialog1 .Title = "Open text file";
openFileDialog1 .InitialDirecto ry = @"c:\";
openFileDialog1 .Filter = "txt files (*.txt)|*.txt|A ll
files (*.*)|*.*";
if (openFileDialog 1.ShowDialog() == DialogResult.OK )
{
try
{
if ((myStream = openFileDialog1 .OpenFile()) !=
null)
{
using (myStream)
{
StreamReader sr =
File.OpenText(o penFileDialog1. FileName);
myPrintFilename =
openFileDialog1 .FileName;
string s = sr.ReadLine();
StringBuilder sb = new StringBuilder() ;
while (s != null)
{
sb.Append(s);
myGlobalStringB uilder.AppendLi ne(s);
s = sr.ReadLine();
myGlobalStringB uilder.AppendLi ne(s);
Debug.WriteLine ("Hi");
}
sr.Close();
textBox1.Text = sb.ToString();
//
myGlobalStringB uilder.Append(s b.ToString()); //wrong
}
}
}
catch (Exception ex)
{
MessageBox.Show ("Error: could not read file from
disk (myStream); Err: " + ex.Message);
}
}
}
// // this is code that you need to save a file. Not really relevant
for the 'infinite loop' problem above, but I include for Pavel
private void saveToolStripBu tton_Click(obje ct sender,
EventArgs e)
{
// SaveFileDialog saveFileDialog1 = new SaveFileDialog( ); //
not needed
SaveFileDialog MySaveFileDialo g = new SaveFileDialog( );
MySaveFileDialo g.Filter = "txt files (*.txt)|*.txt|A ll
files (*.*)|*.*";
MySaveFileDialo g.DefaultExt = "txt";
MySaveFileDialo g.FilterIndex = 2;
MySaveFileDialo g.RestoreDirect ory = true;
if (MySaveFileDial og.ShowDialog() == DialogResult.OK )
{
using (Stream myStream = MySaveFileDialo g.OpenFile())
{
if (myStream != null)
{
using (StreamWriter myWritter = new
StreamWriter(my Stream, System.Text.Enc oding.ASCII))
{
myWritter.Write (textBox1.Text) ;
}
}
}
}
}
private void printDocument1_ BeginPrint(obje ct sender,
System.Drawing. Printing.PrintE ventArgs e)
{
//can go here to avoid having to do this for every page
(since same for every page)
////Hence we have created the Font, SolidBrush and
StringFormat objects in the handler for the BeginPrint event. Note
that we could have done this in the handler of the PrintPage event as
well but then these objects would have been created for each page
f = new Font("Arial", 12, FontStyle.Regul ar);
b = new SolidBrush(Colo r.Black);
strformat.Trimm ing = StringTrimming. Word;
}
private void printDocument1_ QueryPageSettin gs(object sender,
System.Drawing. Printing.QueryP ageSettingsEven tArgs e)
{
//set margins to 0.5" all around p. 305 Chris Sells
// e.PageSettings. Margins = new Margins(50, 50, 50, 50); //
does not really help much it seems, but does not hurt either
}
}
}