我每天都在努力學習有關 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;
}
我希望我能正確描述我的問題。
uj5u.com熱心網友回復:
您可以修改 CaptureScreen 方法以回傳 Bitmap 變數 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;
}
}
然后在表單類中,您可以進行賦值,因為 Bitmap 繼承自 Image
namespace CatchAreaToImage
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
picturebox1.Image = Screenshot.CaptureScreen();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/364115.html
