【问题标题】:Get and Set Image to Picturebox when Image was creating in other class在其他类中创建图像时获取并将图像设置为图片框
【发布时间】:2022-01-02 06:42:32
【问题描述】:

我每天都在尝试学习有关 C# 的新知识。现在我试图从桌面获取图像,我在另一堂课上做了。现在我不知道这将如何工作。如何获取在我的 screenshot.cs 中创建的图像,以便我可以将其设置为我的 Form1.cs 中的图片框

我的代码是这样的:

namespace CatchAreaToImage
{

    public partial class Form1 : Form
    {

        Bitmap screen;

          
        public Form1()
        {

            InitializeComponent();
        }
        Bitmap screen2;
        private void button1_Click(object sender, EventArgs e)
        {
            Screenshot.CaptureScreen(screen2);

            pBArea.Image = screen2;


        }

我的 Screenshot.cs 是这样的:

    class Screenshot
    {

        public static void CaptureScreen() //do screenshot of desktop
        {
            // Take an image from the screen
            Bitmap screen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); // Create an empty bitmap with the size of the current screen 

            Graphics graphics = Graphics.FromImage(screen as Image); // Create a new graphics objects that can capture the screen

            graphics.CopyFromScreen(0, 0, 0, 0, screen.Size); // Screenshot moment → screen content to graphics object

        }

    }
        public void Image(Bitmap screen)
        {
            screen2 = screen;
        }

我希望我能正确描述我的问题。

【问题讨论】:

  • 您是否考虑过将位图返回给调用者?
  • 试过了......但我的变量总是为空。像这样:在 form1.cs ( public void Image(Bitmap screen) { screen2 = screen; } 中,我将我的类方法更改为 CaptureScreen(Bitmap bitmap) 并使用 Form1 f = new Form1(); f.Image(bitmap ); -> 但这不起作用,因为我的变量为空 //edit 我在第一篇文章中编辑了我的代码

标签: c# class picturebox


【解决方案1】:

您可以修改您的 CaptureScreen 方法以返回位图变量 screen 并将其分配给 pictureBox.Image 属性。

class Screenshot
{
    public static Image CaptureScreen()
    {
        
        Bitmap screen = new Bitmap(
            Screen.PrimaryScreen.Bounds.Width, 
            Screen.PrimaryScreen.Bounds.Height);

        Graphics graphics = Graphics.FromImage(screen as Image);

        graphics.CopyFromScreen(0, 0, 0, 0, screen.Size); 

        return screen;
    }
}

然后在表单类中,您可以进行分配,因为位图继承自 Image

namespace CatchAreaToImage
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Image screen = Screenshot.CaptureScreen(); 
            this.pictureBox1.Image = screen;
            // other uses of screen possible
        }
    }
}

【讨论】:

  • 是的,谢谢,这行得通:) 但是是否可以将屏幕的值设置为另一个变量,然后将其放在picturebox1.image 之后?像picturebox1.image = screen2?
  • 是的,您可以将函数的返回值分配给 button1_Click 范围内的新变量,并像这样多次分配它 Image screen = Screenshot.CaptureScreen(); this.pictureBox1.Image = 屏幕; this.pictureBox2.Image = 屏幕;这是你想要的吗?
  • 是的,这就是我想要的。谢谢
猜你喜欢
  • 2015-05-27
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多