Search code examples
.netwinformsscreen-capturedelphi-prism

How to screen capture a winform hidden behind another winform?


I need to screen capture a winform that is either behind or in front of another window and nothing else.

I am able to screen capture a winform but it basically captures anything and everything in that area.

Here is how I screen capture.

method ControlWin.capturescreen;
begin
        var myGraphics := self.CreateGraphics;
        var memoryGraphics := self.CreateGraphics;
        var s := self.Size;
        ControlScreen := new Bitmap(s.Width, s.Height, myGraphics);
        memoryGraphics := Graphics.FromImage(ControlScreen);
        memoryGraphics.CopyFromScreen(self.Location.X, self.Location.Y, 0, 0, s);
end;

Here is how it looks:

enter image description here

Any hints or clues in C# or delphi-prism will be greatly appreciated. Thanks,


Solution

  • This does the trick in C#.

    _onTopForm is a second form with TopMost set to true. Place it over Form1.

    Click the button and the screenshot of Form1 is written to disk. _onTopForm will not be in the screenshot.

    public partial class Form1 : Form
    {
        readonly OnTopForm _onTopForm = new OnTopForm();
    
        public Form1()
        {
            InitializeComponent();
            _onTopForm.Show();
            _onTopForm.TopMost = true;
        }
    
        private void Button1Click(object sender, EventArgs e)
        {
            Bitmap bmp = new Bitmap(Width, Height);
            DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
    
            using (FileStream fs = new FileStream("C:\\temp\\screenshot.jpeg", FileMode.OpenOrCreate))
            {
                bmp.Save(fs, ImageFormat.Jpeg);
            }
        }
    }
    
    public partial class OnTopForm : Form
    {
        public OnTopForm()
        {
            InitializeComponent();
        }
    }