I'm trying the same
try this code but my problem is
1- getting the actual screen scale and layout to get the actual form size and location for example my screen size 1920 * 1080 with scale 125%
when I try to get
var screenWidth = SystemParameters.PrimaryScreenWidth;
var screenHeight = SystemParameters.PrimaryScreenHeight;
I got the result
screenWidth = 1920/54 = 1536 , screenHeight = 1080/54 = 864
so till now you will need to adjusted manually like I did
int captureX = pictureBox2.Location.X / 4 * 5 + this.Location.X / 4 * 5;
int captureY = pictureBox2.Location.Y / 4 * 5 + this.Location.Y / 4 * 5;
2- CopyFromScreen copy the entire screen including the form so in order to capture the area behind the form you must add opacity = 0 ; then opacity =1 ;
or using this.Visible = false; and this.Visible = true; which causes flickering when moving the form
private void CaptureResizeAndSetBackgroundpictureBox()
{
//// Define the capture area (e.g., the entire screen or a specific region)
//int captureX = pictureBox2.Location.X + pictureBox2.Location.X / 4;
//int captureY = pictureBox2.Location.Y + pictureBox2.Location.Y / 4;
//int captureWidth = pictureBox2.Width + pictureBox2.Width / 4; // Width of the form
//int captureHeight = pictureBox2.Height + pictureBox2.Height / 4; // Height of the form
this.Visible = false;
int captureX = pictureBox2.Location.X / 4 * 5 + this.Location.X / 4 * 5;
int captureY = pictureBox2.Location.Y / 4 * 5 + this.Location.Y / 4 * 5;
int captureWidth = pictureBox2.Width + pictureBox2.Width / 4; // Width of the form
int captureHeight = pictureBox2.Height + pictureBox2.Height / 4; // Height of the form
// Capture the screen within the defined area
// Bitmap capturedImage = new Bitmap(captureWidth, captureHeight);
Bitmap capturedImage = new Bitmap(captureWidth, captureHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (Graphics captureGraphics = Graphics.FromImage(capturedImage))
{
captureGraphics.CopyFromScreen(captureX, captureY, 0, 0, new Size(captureWidth, captureHeight));
}
// Resize the captured image if needed (optional)
int newWidth = pictureBox2.Width; // Set your desired new width
int newHeight = pictureBox2.Height; // Set your desired new height
if (capturedImage.Width != newWidth || capturedImage.Height != newHeight)
{
capturedImage = new Bitmap(capturedImage, newWidth, newHeight);
}
// capturedImage.MakeTransparent(capturedImage.GetPixel(this.Location.X, this.Location.Y));
// Set the resized image as the background of the form
pictureBox2.Image = capturedImage;
this.Visible = true;
}