locked
FAQs:怎样捕捉到一个进程主窗口的截图? RRS feed

答案

  • 这是一个抓取进程截图的的方法。我们将使用”Notepad”作为例子。请按照下面的步骤:
    1. 使用System.Diagnostics.Process.MainWindowHandle获取需要截图的进程信息。
    2. 使用Windows API函数——SetForegroudWindow获得目标进程。
    3. 传递窗口句柄作为Windows API函数GetWindowRect的第一个参数,获得目标进程的本地信息。
    4. 用第3步中的本地信息定义进程窗口在屏幕的坐标。
    5. 使用第4步中的坐标和Graphics.CopyFromScreen获得截图。

        public partial class Form1 : Form
        {
            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
            [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool SetForegroundWindow(IntPtr hWnd);
            [StructLayout(LayoutKind.Sequential)]
            public struct RECT
            {
                public int Left;
                public int Top;
                public int Right;
                public int Bottom;
            }
            private void button1_Click(object sender, EventArgs e)
            {
                Process proc = new Process();
                proc.StartInfo.FileName = "notepad.exe";
                proc.Start()
                proc.WaitFoInputIdle();
                if (SetForegroundWindow(proc.MainWindowHandle))
                {
                    RECT srcRect;
                    if (!proc.MainWindowHandle.Equals(IntPtr.Zero))
                    {
                        if (GetWindowRect(proc.MainWindowHandle, out srcRect))
                        {
                            int width = srcRect.Right - srcRect.Left;
                            int height = srcRect.Bottom - srcRect.Top;

                            Bitmap bmp = new Bitmap(width, height);
                            Graphics screenG = Graphics.FromImage(bmp);

                            try
                            {
                                screenG.CopyFromScreen(srcRect.Left, srcRect.Top,  
                                        0, 0, new Size(width, height),
                                        CopyPixelOperation.SourceCopy);

                                bmp.Save("notepad.jpg", ImageFormat.Jpeg);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                            finally
                            {
                                screenG.Dispose();
                                bmp.Dispose();
                            }                    
                         }
                     }
                }
            }
        }
    相关的帖子:
    http://social.msdn.microsoft.com/forums/en-US/Vsexpressvcs/thread/3571babb-e20c-4c38-94ff-a49bc0c92e56/


    如果您对我们的论坛在线支持服务有任何的意见或建议,请通过邮件告诉我们。
    MSDN 论坛好帮手 立刻免费下载  MSDN 论坛好帮手
    2011年3月2日 10:48