现在可以在桌面上进行绘画了,但是当何时进行重绘,现在还没有解决方法。
using System;
using System.Runtime.InteropServices;
using System.Drawing;
namespace WindowsApplication2
{
public class WinScreen
{
[DllImport("gdi32.dll")]
static extern IntPtr CreateDC(string lpDriverName, string lpDeviceName, string lpOutput, string lpInitData);
[DllImport("gdi32.dll")]
static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32.dll")]
static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);
[DllImport("gdi32.dll")]
static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
[DllImport("gdi32.dll")]
static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[DllImport("gdi32.dll")]
static extern int BitBlt(IntPtr desthDC, int srcX, int srcY, int srcW, int srcH, IntPtr srchDC, int destX, int destY, int op);
[DllImport("gdi32.dll")]
static extern int DeleteDC(IntPtr hDC);
[DllImport("gdi32.dll")]
static extern int DeleteObject(IntPtr hObj);
public static Bitmap CaptureControl(IntPtr SourceDC,int SourceWidth,int SourceHeight)
{
return Capture(SourceDC,SourceWidth,SourceHeight);
}
public static Bitmap CaptureScreen()
{
IntPtr screen=CreateDC("DISPLAY", "", "", "");
int sourceWidth=GetDeviceCaps(screen, 8);
int sourceHeight=GetDeviceCaps(screen, 10);
Capture(screen,sourceWidth,sourceHeight);
Bitmap ret=Capture(screen,sourceWidth,sourceHeight);
DeleteDC(screen);
return ret;
}
static Bitmap Capture(IntPtr SourceDC,int SourceWidth,int SourceHeight)
{
IntPtr destDC;
IntPtr BMP, BMPOld;
destDC = CreateCompatibleDC(SourceDC);
BMP = CreateCompatibleBitmap(SourceDC, SourceWidth, SourceHeight);
BMPOld = SelectObject(destDC, BMP);
BitBlt(destDC, 0, 0, SourceWidth, SourceHeight, SourceDC, 0, 0, 13369376);
BMP = SelectObject(destDC, BMPOld);
DeleteDC(destDC);
Bitmap ret = Image.FromHbitmap(BMP);
DeleteObject(BMP);
return ret;
}
//在桌面上进行输出的代码
public static void PrintScreen()
{
System.Windows.Forms.SendKeys.Send("{PRTSC}");
System.Windows.Forms.IDataObject obj=System.Windows.Forms.Clipboard.GetDataObject();
if(obj==null) return;
if(obj.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap))
{
Image img=(Bitmap)obj.GetData(System.Windows.Forms.DataFormats.Bitmap);
IntPtr screen=CreateDC("DISPLAY", "", "", "");
IntPtr destDC;
destDC = CreateCompatibleDC(screen);
Graphics g=Graphics.FromHdc(screen,destDC);
g.DrawImage(img,200,100);
DeleteDC(screen);
}
}
}
}
//调用代码
private void button1_Click(object sender, System.EventArgs e)
{
Bitmap bitmap=WinScreen.CaptureControl(button1.CreateGraphics().GetHdc(),button1.Width,button1.Height);
bitmap.Save(@"c:/1.bmp");
bitmap=WinScreen.CaptureScreen();
bitmap.Save(@"c:/2.bmp");
WinScreen.PrintScreen();
}
可以试一下来看看