【问题标题】:How can I get screenshot of a specific window in C#?如何在 C# 中获取特定窗口的屏幕截图?
【发布时间】:2021-02-10 21:12:50
【问题描述】:

我使用 C# 中的 Graphics 类编写了一个截取屏幕截图的代码。代码-

Bitmap bitmapScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Width, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics graphicsScreenshot = Graphics.FromImage(bitmapScreenshot);
graphicsScreenshot.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);

虽然我找不到对任何打开的应用程序/窗口执行相同操作的方法,但有没有办法使用 Graphics 类来执行此操作,如果不在 Graphics 类中,我该怎么做?任何帮助表示赞赏。

【问题讨论】:

    标签: c# graphics bitmap window screenshot


    【解决方案1】:

    您需要像这样将要截屏的目标应用程序窗口带到前台:

    [DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
    public static extern IntPtr FindWindow(String lpClassName, String lpWindowName);
    
    [DllImport("USER32.DLL")]
    public static extern bool SetForegroundWindow(IntPtr hWnd);
    
    public static void bringToFront(string title) {
        // Get a handle to the Calculator application.
        IntPtr handle = FindWindow(null, title);
    
        // Verify that Calculator is a running process.
        if (handle == IntPtr.Zero) {
            return;
        }
    
        // Make Calculator the foreground application
        SetForegroundWindow(handle);
    }
    

    一旦窗口位于前台,您可以截屏,这样您的代码将如下所示:

    bringToFront("<Your target app window name>");
    Bitmap bitmapScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Width, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
    Graphics graphicsScreenshot = Graphics.FromImage(bitmapScreenshot);
    graphicsScreenshot.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-11
      • 2020-12-30
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多