我在程序中制作了一个打印按钮,我的意图是打印带有文本、图像和变量内容的不同行和列。
我已经研究了图形方法并进行了下面的代码所示的测试。我在另一个方法中定义了一些变量,我想在字符串旁边打印这些变量的内容。任何人都可以指导如何使用图形方法吗?
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);
}
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
中调用它。
编辑(更新的代码)
您的代码似乎只是数学范围的,但计算和打印也将从两个不同的按钮分别触发。
因此,在这种情况下,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
}
希望这有帮助!