zoukankan      html  css  js  c++  java
  • 用Java和C#编写一个截屏小程序

    首先看看Java是如何实现的:
    主要使用的是java.util.Robot类来捕获屏幕,可以实现对屏幕一个矩形区域的捕获,通过这个类,我们也可以实现一个远程桌面控制的程序

      1package com.qiu.util;
      2import java.io.*;
      3import java.net.*;
      4import javax.swing.*;
      5import java.awt.*;
      6import java.awt.event.*;
      7import java.awt.image.*;
      8import javax.imageio.*;
      9import java.io.*;
     10
     11
     12
     13/**@Author Qiu_BaiChao
     14 *一个简单的屏幕抓图
     15 *
     16 **/

     17 
     18public class ScreenCapture {
     19 //test main
     20 public static void main(String[] args) throws Exception{
     21  String userdir = System.getProperty("user.dir");
     22  File tempFile = new File("d:","temp.png"); 
     23  ScreenCapture capture = ScreenCapture.getInstance();
     24  capture.captureImage();  
     25  JFrame frame = new JFrame();
     26  JPanel panel = new JPanel();
     27  panel.setLayout(new BorderLayout());
     28  JLabel imagebox = new JLabel();
     29  panel.add(BorderLayout.CENTER,imagebox);  
     30  imagebox.setIcon(capture.getPickedIcon());
     31  capture.saveToFile(tempFile);
     32  capture.captureImage();
     33  imagebox.setIcon(capture.getPickedIcon());
     34  frame.setContentPane(panel);
     35  frame.setSize(400,300);
     36  frame.show();
     37  System.out.println("Over");
     38 }

     39 
     40 private ScreenCapture() {
     41  
     42  try{
     43   robot = new Robot();
     44  }

     45  catch(AWTException e) {
     46   System.err.println("Internal Error: " + e);
     47   e.printStackTrace();
     48  }
      
     49  JPanel cp = (JPanel)dialog.getContentPane();
     50  cp.setLayout(new BorderLayout());  
     51  labFullScreenImage.addMouseListener(new MouseAdapter() {
     52    public void mouseReleased(MouseEvent evn) {
     53      isFirstPoint = true;
     54      pickedImage = fullScreenImage.getSubimage(recX,recY,recW,recH);
     55      dialog.setVisible(false);     
     56    }

     57   }
    );
     58   
     59  labFullScreenImage.addMouseMotionListener(new MouseMotionAdapter() {
     60    public void mouseDragged(MouseEvent evn) {
     61     if(isFirstPoint) {
     62      x1 = evn.getX();
     63      y1 = evn.getY();
     64      isFirstPoint = false;  
     65     }

     66     else {
     67      x2 = evn.getX();
     68      y2 = evn.getY();
     69      int maxX = Math.max(x1,x2);
     70      int maxY = Math.max(y1,y2);
     71      int minX = Math.min(x1,x2);
     72      int minY = Math.min(y1,y2);
     73      recX = minX;
     74      recY = minY;
     75      recW = maxX-minX;
     76      recH = maxY-minY;
     77      labFullScreenImage.drawRectangle(recX,recY,recW,recH);    
     78     }

     79    }

     80    
     81    public void mouseMoved(MouseEvent e) {
     82     labFullScreenImage.drawCross(e.getX(),e.getY());
     83    }

     84   }
    );
     85   
     86  cp.add(BorderLayout.CENTER,labFullScreenImage);
     87  dialog.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
     88  dialog.setAlwaysOnTop(true);
     89  dialog.setMaximumSize(
     90   Toolkit.getDefaultToolkit().getScreenSize());
     91  dialog.setUndecorated(true);
     92  dialog.setSize(dialog.getMaximumSize());
     93  dialog.setModal(true);
     94 }

     95 //Singleton Pattern
     96 public static ScreenCapture getInstance() {
     97  return defaultCapturer;
     98 }

     99 /**捕捉全屏慕*/
    100 public Icon captureFullScreen() {
    101  fullScreenImage = robot.createScreenCapture(new Rectangle(
    102   Toolkit.getDefaultToolkit().getScreenSize()));
    103  ImageIcon icon = new ImageIcon(fullScreenImage);
    104  return icon;
    105 }

    106 /**捕捉屏幕的一个矫形区域
    107  */

    108 public void captureImage() {
    109  fullScreenImage = robot.createScreenCapture(new Rectangle(
    110   Toolkit.getDefaultToolkit().getScreenSize()));
    111  ImageIcon icon = new ImageIcon(fullScreenImage);
    112  labFullScreenImage.setIcon(icon);  
    113  dialog.setVisible(true); 
    114 }

    115 /**得到捕捉后的BufferedImage*/ 
    116 public BufferedImage getPickedImage() {
    117  return pickedImage;
    118 }

    119 /**得到捕捉后的Icon*/ 
    120 public ImageIcon getPickedIcon() {
    121  return new ImageIcon(getPickedImage());
    122 }

    123 /**储存为一个文件,为PNG格式
    124  *@deprecated
    125  *replaced by saveAsPNG(File file)
    126  **/

    127 @Deprecated
    128 public void saveToFile(File file) throws IOException{
    129  ImageIO.write(getPickedImage(),defaultImageFormater,file);
    130 }

    131 /**储存为一个文件,为PNG格式*/
    132 public void saveAsPNG(File file) throws IOException {
    133  ImageIO.write(getPickedImage(),"png",file);
    134 }

    135 /**储存为一个JPEG格式图像文件*/
    136 public void saveAsJPEG(File file) throws IOException {
    137  ImageIO.write(getPickedImage(),"JPEG",file);
    138 }

    139 
    140 /**写入一个OutputStream*/
    141 public void write(OutputStream out) throws IOException{
    142  ImageIO.write(getPickedImage(),defaultImageFormater,out);
    143 }

    144 
    145 //singleton design pattern
    146 private static ScreenCapture defaultCapturer = new ScreenCapture(); 
    147 private int x1,y1,x2,y2;
    148 private int recX,recY,recH,recW; //截取的图像
    149 private boolean isFirstPoint  = true;
    150 private BackgroundImage labFullScreenImage = new BackgroundImage();
    151 private Robot robot;
    152 private BufferedImage fullScreenImage;
    153 private BufferedImage pickedImage;
    154 private String defaultImageFormater = "png";
    155 private JDialog dialog = new JDialog();
    156}

    157
    158
    159
    160/**显示图片的Label*/
    161class BackgroundImage extends JLabel{
    162 public void paintComponent(Graphics g) {
    163  super.paintComponent(g);
    164  g.drawRect(x,y,w,h);
    165  String area = Integer.toString(w)+" * "+ Integer.toString(h);
    166  g.drawString(area,x+(int)w/2-15,y+(int)h/2);
    167  g.drawLine(lineX,0,lineX,getHeight());
    168  g.drawLine(0,lineY,getWidth(),lineY);
    169 }

    170 
    171 public void drawRectangle(int x,int y,int width,int height) {
    172  this.x = x;
    173  this.y = y;
    174  h = height;
    175  w = width;
    176  repaint();
    177 }

    178 
    179 public void drawCross(int x,int y) {
    180  lineX = x;
    181  lineY = y;
    182  repaint();
    183 }

    184 
    185 int lineX,lineY;
    186 int x,y,h,w;
    187}

    188
    189

    那么,然后我们来做一个C#实现的截屏,注意,调用完全是MS的API:

    用ScreenCapture这个类特别简单,该类有四个方法:

    • public Image CaptureScreen()
      捕获整个屏幕的图象
    • public Image CaptureWindow(IntPtr handle)
      捕获窗口上的图象
    • public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format)
      捕获窗口图像并且保存为一个文件
    • public void CaptureScreenToFile(string filename, ImageFormat format)
      捕获整个屏幕的图像并且保存为一个文件

        1using System;
        2using System.Runtime.InteropServices;
        3using System.Drawing;
        4using System.Drawing.Imaging;
        5
        6namespace ScreenShotDemo
        7{
        8 /// <summary>
        9 /// 提供捕获全屏或者一个不规则窗口函数,并保存。
       10 /// </summary>

       11 public class ScreenCapture
       12 {
       13        /// <summary>
       14        /// Creates an Image object containing a screen shot of the entire desktop?
       15        /// </summary>
       16        /// <returns></returns>

       17        public Image CaptureScreen() 
       18        {
       19            return CaptureWindow( User32.GetDesktopWindow() );
       20        }

       21
       22        /// <summary>
       23        /// Creates an Image object containing a screen shot of a specific window?
       24        /// </summary>
       25        /// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
       26        /// <returns></returns>

       27        public Image CaptureWindow(IntPtr handle)
       28        {
       29            // get te hDC of the target window
       30            IntPtr hdcSrc = User32.GetWindowDC(handle);
       31            // get the size
       32            User32.RECT windowRect = new User32.RECT();
       33            User32.GetWindowRect(handle,ref windowRect);
       34            int width = windowRect.right - windowRect.left;
       35            int height = windowRect.bottom - windowRect.top;
       36            // create a device context we can copy to
       37            IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
       38            // create a bitmap we can copy it to,
       39            // using GetDeviceCaps to get the width/height
       40            IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height); 
       41            // select the bitmap object
       42            IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap);
       43            // bitblt over
       44            GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY);
       45            // restore selection
       46            GDI32.SelectObject(hdcDest,hOld);
       47            // clean up 
       48            GDI32.DeleteDC(hdcDest);
       49            User32.ReleaseDC(handle,hdcSrc);
       50
       51            // get a .NET image object for it
       52            Image img = Image.FromHbitmap(hBitmap);
       53            // free up the Bitmap object
       54            GDI32.DeleteObject(hBitmap);
       55
       56            return img;
       57        }

       58
       59        /// <summary>
       60        /// Captures a screen shot of a specific window, and saves it to a file?
       61        /// </summary>
       62        /// <param name="handle"></param>
       63        /// <param name="filename"></param>
       64        /// <param name="format"></param>

       65        public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format) 
       66        {
       67            Image img = CaptureWindow(handle);
       68            img.Save(filename,format);
       69        }

       70
       71        /// <summary>
       72        /// Captures a screen shot of the entire desktop, and saves it to a file?
       73        /// </summary>
       74        /// <param name="filename"></param>
       75        /// <param name="format"></param>

       76        public void CaptureScreenToFile(string filename, ImageFormat format) 
       77        {
       78            Image img = CaptureScreen();
       79            img.Save(filename,format);
       80        }

       81       
       82        /// <summary>
       83        /// Helper class containing Gdi32 API functions
       84        /// </summary>

       85        private class GDI32
       86        {
       87            
       88            public const int SRCCOPY = 0x00CC0020// BitBlt dwRop parameter
       89
       90            [DllImport("gdi32.dll")]
       91            public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest,
       92                int nWidth,int nHeight,IntPtr hObjectSource,
       93                int nXSrc,int nYSrc,int dwRop);
       94            [DllImport("gdi32.dll")]
       95            public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth, 
       96                int nHeight);
       97            [DllImport("gdi32.dll")]
       98            public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
       99            [DllImport("gdi32.dll")]
      100            public static extern bool DeleteDC(IntPtr hDC);
      101            [DllImport("gdi32.dll")]
      102            public static extern bool DeleteObject(IntPtr hObject);
      103            [DllImport("gdi32.dll")]
      104            public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject);
      105        }

      106 
      107        /// <summary>
      108        /// Helper class containing User32 API functions
      109        /// </summary>

      110        private class User32
      111        {
      112            [StructLayout(LayoutKind.Sequential)]
      113            public struct RECT
      114            {
      115                public int left;
      116                public int top;
      117                public int right;
      118                public int bottom;
      119            }

      120
      121            [DllImport("user32.dll")]
      122            public static extern IntPtr GetDesktopWindow();
      123            [DllImport("user32.dll")]
      124            public static extern IntPtr GetWindowDC(IntPtr hWnd);
      125            [DllImport("user32.dll")]
      126            public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);
      127            [DllImport("user32.dll")]
      128            public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect);
      129
      130        }

      131
      132
      133 }

      134}

      135
      136

      本文很多源代码来自http://www.planet-source-code.com/
      提供很多不错的Source。

  • 相关阅读:
    leetcode刷题-131~
    leetcode刷题-106~114/116~122/125/127/129~130
    leetcode刷题-100~105
    Intel-Pin的windows安装
    九、appium自动化框架综合实践
    QQ传文件用例设计
    mysql常用语句
    谐云试用的日子
    码农开发资料集
    MyBatis中一个SQL语句的执行过程解析
  • 原文地址:https://www.cnblogs.com/SlashOut/p/273802.html
Copyright © 2011-2022 走看看