Is there a way to take a screenshot of the user's Windows desktop?

前端 未结 5 1841
孤独总比滥情好
孤独总比滥情好 2020-12-08 22:08

I want to provide the user with a scaled-down screenshot of their desktop in my application.

Is there a way to take a screenshot of the current user\'s Windo

5条回答
  •  时光取名叫无心
    2020-12-08 22:48

    I get the impression that you are shooting for taking a picture of the actual desktop (with wallpaper and icons), and nothing else.

    1) Call ToggleDesktop() in Shell32 using COM
    2) Use Graphics.CopyFromScreen to copy the current desktop area
    3) Call ToggleDesktop() to restore previous desktop state

    Edit: Yes, calling MinimizeAll() is belligerent.

    Here's an updated version that I whipped together:

        /// 
        /// Minimizes all running applications and captures desktop as image
        /// Note: Requires reference to "Microsoft Shell Controls and Automation"
        /// 
        /// Image of desktop
        private Image CaptureDesktopImage() {
    
            //May want to play around with the delay.
            TimeSpan ToggleDesktopDelay = new TimeSpan(0, 0, 0, 0, 150);
    
            Shell32.ShellClass ShellReference = null;
    
            Bitmap WorkingImage = null;
            Graphics WorkingGraphics = null;
            Rectangle TargetArea = Screen.PrimaryScreen.WorkingArea;
            Image ReturnImage = null;
    
            try
            {
    
                ShellReference = new Shell32.ShellClass();
                ShellReference.ToggleDesktop();
    
                System.Threading.Thread.Sleep(ToggleDesktopDelay);
    
                WorkingImage = new Bitmap(TargetArea.Width,
                    TargetArea.Height);
    
                WorkingGraphics = Graphics.FromImage(WorkingImage);
                WorkingGraphics.CopyFromScreen(TargetArea.X, TargetArea.X, 0, 0, TargetArea.Size);
    
                System.Threading.Thread.Sleep(ToggleDesktopDelay);
                ShellReference.ToggleDesktop();
    
                ReturnImage = (Image)WorkingImage.Clone();
    
            }
            catch
            {
                System.Diagnostics.Debugger.Break();
                //...
            }
            finally
            {
                WorkingGraphics.Dispose();
                WorkingImage.Dispose();
            }
    
            return ReturnImage;
    
        }
    

    Adjust to taste for multiple monitor scenarios (although it sounds like this should work just fine for your application).

提交回复
热议问题