You are on page 1of 17

9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

DOTNETTRICKS
HandyTricksandTipstodoyour.NETcodeFast,Efficientand
Simple.Somecommonquestionsthatcomesintomind.Please
checkifyoucouldfindthemlistedornot.

HOME ABOUTME PEOPLEIADMIRE CODEPROJECT DOTNETFUNDA DAILYDOTNETTIPS

MYINTERVIEW FAQ WPFTUTORIAL C#INTERNALS FORUM

ScreenCaptureinWPF&WinForms
Application
PostedbyAbhishekSuronMonday,April12,2010
Labels:.NET,CodeProject,WinForms,WPF 4Comments

Iwaswonderinghowonecancapturescreenshotfroman
application.Isawmanyapplicationwasdoingthem.Thisthought
mademeinterestedtowriteanapplicationthatcantake
ScreenShot.Inthisarticle,Iwilldemonstratehowonecantake
screenshotdirectlyfromtheDesktopareausingWinFormsand
WPF.

WinFormsApplication

InWinFormsapplication,itisveryeasytograbascreen
snapshot.TodothisyouonlyneedtocreateanobjectofBitmap,
onwhichyouwanttodrawtheimage,getGraphicsobjectfrom
theBitmapandthenuseCopyFromScreenmethodtoactually
drawtheimageintotheBitmap.Todemonstrateletusconsider
thismethod:

publicvoidCaptureScreen(doublex,doubley,double
width,doubleheight)
{
intix,iy,iw,ih;
ix=Convert.ToInt32(x);
iy=Convert.ToInt32(y);
iw=Convert.ToInt32(width);
ih=Convert.ToInt32(height);
Bitmapimage=newBitmap(iw,ih,

System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphicsg=Graphics.FromImage(image);

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 1/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

g.CopyFromScreen(ix,iy,ix,iy,
newSystem.Drawing.Size(iw,ih),
CopyPixelOperation.SourceCopy);
SaveFileDialogdlg=newSaveFileDialog();
dlg.DefaultExt="png";
dlg.Filter="PngFiles|*.png";
DialogResultres=dlg.ShowDialog();
if(res==
System.Windows.Forms.DialogResult.OK)
image.Save(dlg.FileName,
ImageFormat.Png);
}

TheabovecodetakesStartX,StartY,widthandheightand
savestheimageintothedisk.Inthismethod,Icreatedanobject
ofBitmapwhereIwouldbegoingtodrawtheimage.Thereare
largenumberofPixelFormatsupportedbytheBitmapobject.
Youcanchooseanyoneofthemwhichsuitsyou.AsIamworking
on32Bittruecolorenvironment,IusedFormat32bppArgb.

Afterdoingthis,youneedtoactuallydrawintotheBitmapobject.
Todothis,youneedtogetgraphicsobjectfromtheimage.I
usedGraphics.FromImage(image)tograbthegraphicsobject
fromtheimage,sothatthegraphicscoulddrawintotheBitmap
object.

FinallyIcalledg.CopyFromScreenwhichactuallycapturesthe
screensnapshot,justlikewhatScreenshotdoesandwriteson
theBitmap.TheargumentthatIhavepasseddeterminesthe
dimensionoftheimage.Thex,y,widthandheightdetermines
wherefromthescreenthesnapshotshouldstartanditswidth
andheightuptowhichitmustgo.Atlast,Iusedimage.Saveto
savetheimageinPngformatinthedisk.

Youshouldnote,ifyouwanttransparencyinyourimage,you
shouldusePNG,asitsupportstransparency.

AlittleDepth

Ifyouwanttoknowwhatexactlyhappensinbackground,letus
useDllImporttodemonstratetheconcept.ActuallyScreen

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 2/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

captureismadeusingaAPIcalltoBitBlt.Thismethodcanbe
calledwithappropriatedimensionjustasthemanagedmethod
CopyFromScreen,andgettheimage.
ToimplementusingNativecode:

internalclassNativeMethods
{

[DllImport("user32.dll")]
publicexternstaticIntPtrGetDesktopWindow();
[DllImport("user32.dll")]
publicstaticexternIntPtrGetWindowDC(IntPtr
hwnd);
[DllImport("user32.dll",CharSet=CharSet.Auto,
ExactSpelling=true)]
publicstaticexternIntPtrGetForegroundWindow();
[DllImport("gdi32.dll")]
publicstaticexternUInt64BitBlt(IntPtrhDestDC,
intx,inty,
intnWidth,intnHeight,IntPtrhSrcDC,
intxSrc,intySrc,System.Int32dwRop);

TheNativeMethodBitBltactuallythemostusefulmethodinthis
context.Tograbtheimageusingthisyoucanuse:

publicvoidSaveScreen(doublex,doubley,double
width,doubleheight)
{
intix,iy,iw,ih;
ix=Convert.ToInt32(x);
iy=Convert.ToInt32(y);
iw=Convert.ToInt32(width);
ih=Convert.ToInt32(height);
try
{
BitmapmyImage=newBitmap(iw,ih);
Graphicsgr1=Graphics.FromImage(myImage);
IntPtrdc1=gr1.GetHdc();
IntPtrdc2=
NativeMethods.GetWindowDC(NativeMethods.GetForegroundWi
ndow());

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 3/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

NativeMethods.BitBlt(dc1,ix,iy,iw,ih,dc2,
ix,iy,13369376);
gr1.ReleaseHdc(dc1);
SaveFileDialogdlg=newSaveFileDialog();
dlg.DefaultExt="png";
dlg.Filter="PngFiles|*.png";
DialogResultres=dlg.ShowDialog();
if(res==
System.Windows.Forms.DialogResult.OK)
myImage.Save(dlg.FileName,
ImageFormat.Png);
}
catch{}
}

Inthisfunction,IamdoingthesamethingthatIdidforthe
earlier.Thedifferenceisthat,hereImausingNativeMethodto
invoketheBitBltdirectlyratherthanusingtheManagedcode
6
CopyFromScreenmethod.
Share
Ifyouwanttocapturethewholeworkingarea,youcanuse
StumbleUpon
Screen.PrimaryScreen.Bounds.X,
Submit
Screen.PrimaryScreen.Bounds.Y,
Screen.PrimaryScreen.Bounds.Width,and
Screen.PrimaryScreen.Bounds.Height
1
asitsarguments.

SampleApplication

Inthissampleapplication,youwillfindaWPFapplicationthat
allowsyoutocaptureapartofthescreen.Letslookhowitworks
:

1.Runtheapplication,youwillbeprovidedwithascreenwhere
youcandragmousetotakescreenshot.

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 4/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

2.AfteryoudragthemouseandReleasethemouse,youwillsee
adialogboxtosavetheimage.

3.Finallyafteryousave,youwillseethesnapshotinpngformat.

ThusitisveryeasytoworkwithScreencapture.

Ihopeyouwilllikethisapplication.

DownloadtheSampleApplication
ScreenShotSample.Zip(50KB)
Shoutit SubmitthisstorytoDotNetKicks
Megusta A6personaslesgustaesto.Registrarteparaverqulesgustaatus
amigos.

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 5/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

ReadDisclaimerNotice

Comments Community
1 Login

Recommend Share SortbyBest

Jointhediscussion

AbhishekSur 6yearsago
Seetakingsnapinstreamingvideowillbeacompletely
differentapproach.Iwillexplainthatinanotherarticle.

Fortimebeingyoucantry
http://www.vbhelper.com/howto...
1 Reply Share

senpisey 3yearsago
thisexampleisverygoodbutwhyiusecan'tMouseUpevenin
WPF?
Reply Share

ashkan 5yearsago
thanksforthecode,thishelpedmealotinwhatI'mtryingto
do.thereisjustoneverysmallthingwhichIthinkyouhaveto
fixinthecodeincaptureScree()insteadof:
g.CopyFromScreen(ix,iy,ix,iy,
newSystem.Drawing.Size(iw,ih),
CopyPixelOperation.SourceCopy)

youshouldput:

g.CopyFromScreen(ix,iy,0,0,
newSystem.Drawing.Size(iw,ih),
CopyPixelOperation.SourceCopy)

becausewewanttocopythecapturedgraphicsto(0,0)ofthe
destinationfile.
Reply Share

Anonymous 6yearsago
Thisisanexcellentarticle,fantasticwork.Justonequestion,I
wanttocreateastreamingapp(similartowhatremote
desktoporremoteassistancedoes).Wouldsimplycapturing
http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 6/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication
desktoporremoteassistancedoes).Wouldsimplycapturing
thewindowcontentsrepeatedlyandstramingbeefiicientif
donethisway?Ifnot,isthereastandardwayofcapturing
windowsinavideoformatthroughdotNet?
Reply Share

ALSOONDOTNETTRICKS

AdvancedUsageofGrouping .NETBook:VisualStudio
inCollectionViewwith 2013ExpertDevelopment
ItemsPresenter
3comments3yearsago Cookbook
4comments2yearsago
Jumbodium Thanksfor SSDNTechnologiesIlove
sharingtheinformation.Itwas theinformationyoupresent
reallyinterestingtoknowsuch here
factsanditwasvery
Home
NewerPost OlderPost

Author'snewbook

Abhishekauthoredoneofthebestsellingbookof.NET.ItcoversASP.NET,
WPF,Windows8,Threading,MemoryManagement,Internals,Visual
Studio,HTML5,JQueryandmanymore...
Grabitnow!!!

Blog
Subscription

Enteryouremail.
Subscribe

Traducir esta pgina Espaol

Microsoft Translator

LearnMVC5step
bystep

Myfriend
ShivprasadKoirala
whoisalsoa
http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 7/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

MicrosoftASP.NET
MVPhasreleased
LearnMVC5stepby
stepvideoseries.It
startsrightfrom
basicsofMVCand
goestoaleveluntil
youbecomea
professional.You
canstarttakingthe
courseforfreeusing
thebelowyoutube
video.

Learn ASP.NET MVC 5

Pleasetryit,youwill
finditawesome.

MyAwards

ClientAppDev


CodeprojectMVP

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 8/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication


Codeproject
Associate


DotnetfundaMVP

HitCounter

Twitter

Best.NET4.5
ExpertCookBook

Abhishekauthored
oneofthebest
sellingbookof.NET.
ItcoversASP.NET,
WPF,Windows8,
Threading,Memory
Management,
Internals,Visual
Studio,HTML5,
JQueryandmany
more...

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 9/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

Grabitnow!!!
Anotherbookon
.NET4.5hasbeen
releasedvery
recently.Itcovers
Debugging,
Testing,
Extensibility,WCF,
WindowsPhone,
WindowsAzureand
manymore...

Grabitnow!!!
GETANYBOOKAT
$5fromPacktPub.
Offerislimited

TheProgrammers
Newspaper

ToGetyourfree
copy,Clickhere.

JointheTEAM

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 10/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

Jointhissite
withGoogleFriend
Connect

Members(138)
More

BlogsIfollow

Daily.NETTips
JonSkeet:Coding
Blog
amazedsaint'stech
journal
AlvinAshcraft's
MorningDew
Abhijit'sWorldof
.NET

BlogArchive

2015(2)
2014(1)
2013(5)
2012(6)
2011(58)
2010(90)
December(6)
November(7)
October(8)
September
(11)
August(11)
July(10)
June(10)
May(8)
April(7)

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 11/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

ItsTimeto
Celebrate
PackURIto
Reference
Component
ScreenCapture
inWPF&
WinForms
Application
Using
SpellChecker
in
TextboxBase
ASP.NETPage
LifeCycle
Video
Workingwith
WebBrowser
inWPF
ArticleSelected
@WindowsCl
ient.net
March(11)
January(1)
2009(5)
2008(4)

Labels

.NET .NET 3.5


.NET 4.0 .NET
4.5 .NET infrastructure
.NET Memory
Management
ADO.NET ALM
architecture
ASP.NET 4.0
asp.net4.5 async Auto
property initialization await
Azure
beyondrelational
blogger tips book C#
C# 6.0 C#5.0

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 12/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

CodeProject
Configuration cookbook
CustomControl Database
debugging design
pattern Developer
Conference DLR
dotnetfunda.com
exceptionfilters expression
bodies functions Extention
Finalize free GC
Geolocator gesture gift
giveaways html5
IDisposable
internals
IObservable. Rx
IsolatedStorage jquery
kinect LOH MEF
Memory Allocation
Metro multithreading MVP
MVVM nameof null
condition Online
Session Patterns
PDC10 Prism push
technology Reflection
Regex scripting silverlight
SOH static class string
interpolation struct Teched
Testing TFS Threading
tips TPL TPL Data Flows
UnityVisual Studio VS2012
WCF WeakReference
Windows Phone
Windows Phone7
Windows8
windowsclient.net
WinForms WinRT

WPFXAML

PopularPosts

Working
with

CollectionViewin

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 13/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

WPF(Filter,Sort,
Group,Navigate)
Ifyouareworking
withWPFforlong,
youmightalready
havecomeacross
withICollectionView.
ItistheprimaryData
objectforanyWPF
lis...

Forum
Guys,Hereisa
forumforyou.Just
dropanySuggestion,
Query,Problem
anythinghere.Iwill
trytosolveit.Please
makesurethatyou
pr...

Design
Patterns
inC#
AsIam
doingalotof
architecturestuffs,
letsdiscussthevery
basicsofdesigninga
goodarchitecture.To
beginwiththis,you
muststar...

IntroducingRibbon
UIControlforWPF
IntroductionAfter
readingPeteBrown
inhisposton2nd
Augannouncingthe
newRibbonUI
featureinhispost,
Announcing:Microsof

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 14/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

tRibbon...

NotifyIconwithWPF
applications
NotifyIconisanutility
form
System.Windows.For
mswhichcanbe
usedbyany
applicationtoinvoke
thedefault
notificationfromthe
systemt...

Writing
a

ReusableCustom
ControlinWPF
Inmypreviouspost,
Ihavealready
definedhowyoucan
inheritfroman
existingcontroland
defineyourown
reusablechunk.The
reusableX...

All
about
.NET
Timers
AComparison
ThreadsandTimers
arethemost
commonthingsthat
youneedforyour
application.Anywork
thatneedstobe
doneinbackground
withoutinter...

WPFTutorial
WPF,a.k.aWindows
Presentation

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 15/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

Foundationprovides
anunifiedmodelfor
producinghighend
graphicalbusiness
applicationeasily
usingnorm...

C#4.0

Features
C#isalanguagewe
workonregularly,it
isalanguagethatwe
lovethemost.Itis
alwaysgoodtosee
updatestosucha
lovelylanguagewh...

Working
With
Prism
4.0
(HelloWorldSample
withMVVM)
Modularityisoneof
theprimaryconcern
whenworkingwitha
bigprojects.Mostof
usthinkofhowwe
canimplementour
applicationthatcou...

Pages

Home
AboutMe
MySkills
Achievements
PeopleIAdmire

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 16/17
9/6/2016 DOTNETTRICKS:ScreenCaptureinWPF&WinFormsApplication

MyPublication
FrequentlyAsked
Questions

ABOUTME JOINMETOGET
UPDATED

ABH I SH E K SU R

Seguir 620

Microsoft MVP, Client


AppDev
Codeproject MVP,
Associate|Dotnetfunda
MVP | Kolkata .NET
Star | Writer
| Technology
Evangelist |
Technology Lover |
Geek|Speaker
V I EW MY CO MP LET E
P R O FI LE

Copyright@DOTNETTRICKSallrightsreserved.AboutContact DisclaimerNotice Home Top

http://www.abhisheksur.com/2010/04/screencaptureusingwpfwinforms.html 17/17

You might also like