截取特定应用程序的屏幕截图

时间:2014-01-20 08:15:08

标签: c# .net windows screenshot

我正在尝试在桌面上截取特定区域(应用程序)的屏幕截图。请检查此代码......

        try
        {
            //Process p = Process.Start("notepad");
            //Process p = Process.GetProcessById(11152);
            if (p == null)
                Console.WriteLine("Got Null");
            else
            {
            IntPtr h = p.Handle;
            SetForegroundWindow(h);
            ShowWindow(h, 9);
            Rect rect = new Rect();
            IntPtr error = GetWindowRect(p.MainWindowHandle, ref rect);
            while (error == (IntPtr)0)
            {
                error = GetWindowRect(p.MainWindowHandle, ref rect);
            }
            Thread.Sleep(2000);
            int width = rect.right - rect.left;
            int height = rect.bottom - rect.top;
            System.IO.FileStream fs = System.IO.File.Create(@"D:\snapshot.jpg");
            Bitmap bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            Graphics.FromImage(bitmap).CopyFromScreen(rect.left, rect.top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy);
            bitmap.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
            fs.Close();
            bitmap.Dispose();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

我在这种方法之外有这个..

    [DllImport("user32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);
    [DllImport("user32.dll")]
    private static extern bool IsIconic(IntPtr hWnd);
    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();
    [DllImport("user32.dll")]
    private static extern IntPtr ShowWindow(IntPtr hWnd, int nCmdShow);
    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

    [StructLayout(LayoutKind.Sequential)]
    public struct Rect
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }

当我尝试打开一个新的应用程序并尝试截取屏幕截图(例如记事本)时,它就像一个魅力。但是,当我尝试截取当前正在运行的应用程序(如任务管理器等)的屏幕截图时,它不起作用(我仍然得到一个小黑色矩形的图像)..请帮助我..

1 个答案:

答案 0 :(得分:0)

更改

IntPtr h = p.Handle;

IntPtr h = p.MainWindowHandle;

并检查。

相关问题