【问题标题】:Access PictureBox from Another Form C# [duplicate]从另一个窗体 C# 访问 PictureBox [重复]
【发布时间】:2016-01-28 15:15:26
【问题描述】:

我正在使用 WinForms。我有两种形式。在 form1 我有一个图片框,在 form2 我有一个打印按钮。我正在尝试构建一个应用程序,该应用程序将使用 Form2 从 Form1 中的图片框中打印图像。

我首先尝试制作一个面板并测试图片是否可以在form1中打印,并且确实可以,但是问题是当将打印代码复制到form2时,代码不允许我访问form1中的图片框。

如何从 Form2 访问 Form1 中的图片框,以便无法打印图片框中的图像。

我在 this.pictureBox1 下收到错误行。

Form2

    private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
       var bmp = new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height);
       this.pictureBox1.DrawToBitmap(bmp, this.pictureBox1.ClientRectangle);
       e.Graphics.DrawImage(bmp, 25, 25, 800, 1050);
    }

【问题讨论】:

  • 你在form2中。所以this.pictureBox1指的是form 2中的图片框,你必须将pictureBox1设为public并在form2中使用
  • 它不是重复的。
  • 并在form2中创建form1的实例? @M.kazemAkhgary
  • 不好的建议是让你的图片框public static。但我认为你不应该担心这一点,因为你只有这两种形式。
  • 我还不完全理解静态的工作原理。对此还是陌生的。您的解决方案正在运行。

标签: c# .net winforms printing picturebox


【解决方案1】:

您可以将 Form1 中的 PictureBox 作为属性传递给 Form2。

我不确定您是如何设置表单以进行加载的。但是,如果您使用的是管理 Form1 和 Form2 的主窗体,则可以执行以下操作。如果您没有主窗体,那么这至少应该让您走上正轨。

Form1

public PictureBox ThePicture
{
    get {return this.pictureBox1; }
}

Form2

private PictureBox _thePicture;
public PictureBox ThePicture
{
    set { this._thePicture = value; }
    get { return this._thePicture; }
}

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
   if (this.ThePicture != null)
   {
       var bmp = new Bitmap(this.ThePicture.Width, this.ThePicture.Height);
       this.ThePicture.DrawToBitmap(bmp, this.ThePicture.ClientRectangle);
       e.Graphics.DrawImage(bmp, 25, 25, 800, 1050);
   }
}

主窗体

Form1 form1 = new Form1();
Form2 form2 = new Form2();
form2.ThePicture = form1.ThePicture;

【讨论】:

  • In var bmp = new Bitmap(this.ThePicture.Width, this.ThePicture.Height);我一直在这个。ThePicture 我得到红色的错误线。属性或索引器“PrinterForm.ThePicture”不能在此上下文中使用,因为它缺少 get 访问器
  • 啊,对,我将缺少的 GET 添加到 Form2 ThePicture。您也可以直接从 printDocument1_PrintPage 中引用 _thePicture 变量。示例:var bmp = new Bitmap(this._thePicture.Width, this._thePicture.Height);
【解决方案2】:

尝试这样做:

//Tente fazer assim:
public Form1()
    {
        InitializeComponent();
    }

    public Image getImagePic
    {
        get 
        {
            return this.pictureBox1.Image;
        }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多