使用windows api实现屏幕截图并复制到剪贴板

最新自动化项目需要使用屏幕截图功能,本来通过autoit发送printscreen键,然后从剪贴板copy出来即可.

require "win32ole"
t = WIN32OLE.new("AutoItX3.Control")
t.Send("{PRINTSCREEN}")
sleep 1
picture=Win32::Clipboard.data(Win32::Clipboard::DIB)
ATT::KeyLog.info "pictrue:#{picture.slice(0..10)}"
File.open("xxx.bmp","wb")do |f|
f.write(picture)
end


 

但是此方法有一定风险,比如在远程桌面连入时,很容易和外部PC的剪贴板混乱.
因此有了使用原始API截图保存的需求.
使用vs2005创建win32控制台程序,勾选ATL即可.注意工程选项,直接静态编译,使程序能适应各个PC.
下面是源码:
带参数时,保存到对应路径,同时复制到剪贴板.
不带参数时,仅复制到剪贴板.

 
// cap.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include
#include


CString GetSuffix(CString strFileName)
{
return strFileName.Right(strFileName.GetLength()-strFileName.ReverseFind('.')-1);
}


int _tmain(int argc, _TCHAR* argv[])
{

wprintf(_T("Useage:
1.capture.exe jpg_path (Save bmp and copy to clipboard.)
2.capture.exe (Only copy bmp to your current clipboard.)
@zc,2012.4.21."));




HWND hwnd = ::GetDesktopWindow();
HDC hDC = ::GetDC(hwnd); //根据窗口来确定截图的大概位置

RECT rect;
::GetClientRect(hwnd, &rect);
HDC hDCMem = ::CreateCompatibleDC(hDC);

HBITMAP hBitMap = ::CreateCompatibleBitmap(hDC, rect.right, rect.bottom);
HBITMAP hOldMap = (HBITMAP)::SelectObject(hDCMem, hBitMap);

::BitBlt(hDCMem, 0, 0, rect.right, rect.bottom, hDC, 0, 0, SRCCOPY); //红色部分确定图片的大小位置

CImage image;
image.Attach(hBitMap);

if (argc==2){
GUID imageFormat = Gdiplus::ImageFormatBMP;
CString suffix = GetSuffix(argv[1]).MakeLower();
if (suffix.Compare(_T("jpg"))==0)
{
imageFormat= Gdiplus::ImageFormatJPEG;
wprintf(_T("img type:jpg"));
}else if (suffix.Compare(_T("png"))==0)
{
imageFormat= Gdiplus::ImageFormatPNG;
wprintf(_T("img type:png"));
}else
{
imageFormat= Gdiplus::ImageFormatBMP;
wprintf(_T("img type:bmp"));
}

image.Save(argv[1],imageFormat);
}

if (OpenClipboard(NULL))
{
EmptyClipboard();
SetClipboardData(CF_BITMAP, image);
CloseClipboard();
}
//::PostMessage(hwnd, WM_KEYDOWN,44 , 0L); //发送 VK_PRINTSCREEN按下的键盘消息

image.Detach();
::SelectObject(hDCMem, hOldMap);
::DeleteObject(hBitMap);
::DeleteDC(hDCMem);
::DeleteDC(hDC);

return 0;
}



 
附件下载:cap_src_vs2005
| 0个评论