主要使用的是java.util.Robot类来捕获屏幕,可以实现对屏幕一个矩形区域的捕获,通过这个类,我们也可以实现一个远程桌面控制的程序
1
package com.qiu.util;
2
import java.io.*;
3
import java.net.*;
4
import javax.swing.*;
5
import java.awt.*;
6
import java.awt.event.*;
7
import java.awt.image.*;
8
import javax.imageio.*;
9
import java.io.*;
10
11
12
13
/**@Author Qiu_BaiChao
14
*一个简单的屏幕抓图
15
*
16
**/
17
18
public 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*/
161
class 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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

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>
11public class ScreenCapture
12{
13/// <summary>
14/// Creates an Image object containing a screen shot of the entire desktop?
15/// </summary>
16/// <returns></returns>
17public Image CaptureScreen()
18{
19return 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>
27public Image CaptureWindow(IntPtr handle)
28{
29// get te hDC of the target window
30IntPtr hdcSrc = User32.GetWindowDC(handle);
31// get the size
32User32.RECT windowRect = new User32.RECT();
33User32.GetWindowRect(handle,ref windowRect);
34int width = windowRect.right - windowRect.left;
35int height = windowRect.bottom - windowRect.top;
36// create a device context we can copy to
37IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
38// create a bitmap we can copy it to,
39// using GetDeviceCaps to get the width/height
40IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height);
41// select the bitmap object
42IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap);
43// bitblt over
44GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY);
45// restore selection
46GDI32.SelectObject(hdcDest,hOld);
47// clean up
48GDI32.DeleteDC(hdcDest);
49User32.ReleaseDC(handle,hdcSrc);
50
51// get a .NET image object for it
52Image img = Image.FromHbitmap(hBitmap);
53// free up the Bitmap object
54GDI32.DeleteObject(hBitmap);
55
56return 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>
65public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format)
66{
67Image img = CaptureWindow(handle);
68img.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>
76public void CaptureScreenToFile(string filename, ImageFormat format)
77{
78Image img = CaptureScreen();
79img.Save(filename,format);
80}
81
82/// <summary>
83/// Helper class containing Gdi32 API functions
84/// </summary>
85private class GDI32
86{
87
88public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter
89
90[DllImport("gdi32.dll")]
91public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest,
92int nWidth,int nHeight,IntPtr hObjectSource,
93int nXSrc,int nYSrc,int dwRop);
94[DllImport("gdi32.dll")]
95public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth,
96int nHeight);
97[DllImport("gdi32.dll")]
98public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
99[DllImport("gdi32.dll")]
100public static extern bool DeleteDC(IntPtr hDC);
101[DllImport("gdi32.dll")]
102public static extern bool DeleteObject(IntPtr hObject);
103[DllImport("gdi32.dll")]
104public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject);
105}
106
107/// <summary>
108/// Helper class containing User32 API functions
109/// </summary>
110private class User32
111{
112[StructLayout(LayoutKind.Sequential)]
113public struct RECT
114{
115public int left;
116public int top;
117public int right;
118public int bottom;
119}
120
121[DllImport("user32.dll")]
122public static extern IntPtr GetDesktopWindow();
123[DllImport("user32.dll")]
124public static extern IntPtr GetWindowDC(IntPtr hWnd);
125[DllImport("user32.dll")]
126public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);
127[DllImport("user32.dll")]
128public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect);
129
130}
131
132
133}
134}
135
136
本文很多源代码来自http://www.planet-source-code.com/
提供很多不错的Source。