我在程序中创建了一个打印按钮,我的意图是用文本,图像和变量内容打印不同的行和列。
我已经查看了Graphics方法,并在下面的代码中进行了测试。我在另一个方法中定义了一些变量,我想在字符串旁边打印这些变量的内容。谁能指导如何使用图形方法?
private void btn_print_Click(object sender, RoutedEventArgs e)
{
try
{
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1169);
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
pd.Print();
}
catch (Exception ex)
{
MessageBox.Show("An error occurred while printing", ex.ToString());
}
}
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
String drawString = "Test";
e.Graphics.DrawString(drawString, new Font("Verdana", 14), new SolidBrush(System.Drawing.Color.Black), 20,20);
}
以下是定义变量的按钮的代码:
private void btn_calculate_Click(object sender, RoutedEventArgs e)
{
int aa = Int32.Parse(tb_windvelocity.Text);
int bb = Int32.Parse(tb_height.Text);
int cc = Int32.Parse(tb_area.Text);
int dd = Int32.Parse(tb_sc.Text);
double ee = Math.Sin((Int32.Parse(tb_angle.Text)) * (Math.PI / 180));
double g = 0;
if (this.cb_gust.SelectedItem==cb_gust1)
{
g = 3;
}
else if(this.cb_gust.SelectedItem == cb_gust2)
{
g = 15;
}
double ff = 5.73 * (Math.Pow(10,-2)) * (Math.Sqrt(1 + (0.15 * aa)));
double gg = aa * (1 + (ff * (Math.Log(bb / 10))));
double hh = 0.06 * (1 + (0.043 * aa)) * Math.Pow((bb / 10), (-0.22));
double ii = gg * (1 - (0.41 * hh * Math.Log(g / 3600)));
double jj1 = (0.5 * 1.225 * dd * cc * Math.Pow(ii, 2) * ee)/1000;
double jj2 = (0.5 * 1.225 * dd * Math.Pow(ii, 2) * ee) / 1000;
lbl_windaction1.Content = Math.Round(jj1,2);
lbl_windaction2.Content = Math.Round(jj2,2);
}
答案 0 :(得分:2)
private string getMyString()
{
return "Hello world";
}
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
String drawString = this.getMyString();
e.Graphics.DrawString(drawString, new Font("Verdana", 14), new SolidBrush(System.Drawing.Color.Black), 20,20);
}
正如TaW所说,您无法访问另一个方法的局部变量,因此您需要定义一个返回变量并在pd_PrintPage
内调用它的方法。
编辑(更新代码)
您的代码似乎只是数学范围,但 calculate 和 print 将分别从两个不同的按钮触发。
因此,在这种情况下,TaW提供的原则正确:
private double jj1, jj2;
private void btn_calculate_Click(object sender, RoutedEventArgs e)
{
double jj1 = // code removed for clarity
double jj2 = // code removed for clarity
this.jj1 = jj1;
this.jj2 = jj2;
}
然后,进入pd_PrintPage
方法:
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
String drawString = this.jj1.ToString();
String drawString2 = this.jj2.ToString();
// now draw with graphics
}
希望这有帮助!