Results 1 to 28 of 28

Thread: VB.NET - Screenshot to jpeg...

  1. #1

    Thread Starter
    Hyperactive Member Libero's Avatar
    Join Date
    Jun 2000
    Location
    Swedish viking
    Posts
    460

    VB.NET - Screenshot to jpeg...

    Im shure this will do the trick for many people.
    VB Code:
    1. Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)
    2.     Private Const VK_SNAPSHOT As Short = &H2Cs
    3.    
    4.    
    5.     Public Function SaveScreen(ByVal theFile As String) As Boolean
    6.         Dim data As IDataObject
    7.         data = Clipboard.GetDataObject()
    8.         Dim bmap As Bitmap
    9.         If data.GetDataPresent(GetType(System.Drawing.Bitmap)) Then
    10.             bmap = CType(data.GetData(GetType(System.Drawing.Bitmap)), Bitmap)
    11.             Me.PictureBox1.Image = bmap
    12.             Me.PictureBox1.Image.Save(theFile, Imaging.ImageFormat.Jpeg)
    13.         End If
    14.     End Function
    15.  
    16.     Private Sub Command2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Command2.Click
    17.         Call keybd_event(System.Windows.Forms.Keys.Snapshot, 0, 0, 0)
    18.         System.Threading.Thread.Sleep(200) ' To have time to catch the clipboard
    19.         SaveScreen("c:\test.jpg")
    20.     End Sub
    Last edited by Libero; Apr 26th, 2004 at 10:13 AM.

  2. #2
    Frenzied Member
    Join Date
    Apr 2003
    Location
    The Future - Skynet
    Posts
    1,157
    With all respect, how come the jpeg is kind of fuzzy?
    I'll Be Back!

    T-1000

    Microsoft .Net 2005
    Microsoft Visual Basic 6
    Prefer using API

  3. #3

    Thread Starter
    Hyperactive Member Libero's Avatar
    Join Date
    Jun 2000
    Location
    Swedish viking
    Posts
    460
    It might be that a jpeg file is a compressed bmp file and therefore might the compression corrupt the file a little bit. If you want to look deeper into this you will have to search for it. I am shure you can choose how much compression you want with coding, but for now the quality of the screenshot will due for me.

  4. #4
    Frenzied Member dynamic_sysop's Avatar
    Join Date
    Jun 2003
    Location
    Ashby, Leicestershire.
    Posts
    1,142
    Originally posted by Liquid Metal
    With all respect, how come the jpeg is kind of fuzzy?
    when the image opens ( usually in Windows PictureViewer ) , try clicking the actuall size button at the bottom the picture should then be clear ( you are seeing a compressed version because it wont show as actuall size by default due to the size of a screenshot )

  5. #5
    Frenzied Member tr333's Avatar
    Join Date
    Nov 2004
    Location
    /dev/st0
    Posts
    1,605

    Re: VB.NET - Screenshot to jpeg...

    wouldnt it be better to save to a PNG file if its a screenshot?
    CSS layout comes in to the 21st century with flexbox!
    Just another Perl hacker,

  6. #6
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Re: VB.NET - Screenshot to jpeg...

    This is a little smoother, and ts 100% framework (no API)...

    VB Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.  
    3.         If Not SaveScreen(Application.StartupPath & "\screen.png") Then
    4.             MessageBox.Show("Sorry dude, couldn't do it.")
    5.         End If
    6.  
    7.     End Sub
    8.  
    9.     Public Function SaveScreen(ByVal theFile As String) As Boolean
    10.  
    11.         Try
    12.             SendKeys.Send("%{PRTSC}")            '<alt + printscreen>
    13.             Application.DoEvents()
    14.  
    15.             Dim data As IDataObject = Clipboard.GetDataObject()
    16.            
    17.             If data.GetDataPresent(GetType(System.Drawing.Bitmap)) Then
    18.                 Dim bmp As Bitmap = CType(data.GetData(GetType(System.Drawing.Bitmap)), Bitmap)
    19.                 bmp.Save(theFile, Imaging.ImageFormat.Png)
    20.             End If
    21.             Clipboard.SetDataObject(0)        'save memory by removing the image from the clipboard
    22.             Return True
    23.         Catch ex As Exception
    24.             Return False
    25.         End Try
    26.  
    27.     End Function
    I don't live here any more.

  7. #7
    New Member
    Join Date
    Mar 2005
    Posts
    1

    Re: VB.NET - Screenshot to jpeg...

    Follow up to WOSSMAN code.

    works great except I keep getting a problem after doing about 8-10 screenshots ! I get an Exception error.

    Further debugging reveals it happens during the .Save command
    The Err.Message is
    "Object reference not set to an instance of an object"

    I would appreciate any feedback since I would love to use this really nice and compact code snippet to do screenshot capture, however I have to capture approximately 100-4000 Screenshots over the span of 60-120minutes.

    Any suggestions would be welcome.
    Sincerely

  8. #8
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Re: VB.NET - Screenshot to jpeg...

    Quote Originally Posted by NSiggel
    Follow up to WOSSMAN code.

    works great except I keep getting a problem after doing about 8-10 screenshots ! I get an Exception error.

    Further debugging reveals it happens during the .Save command
    The Err.Message is
    "Object reference not set to an instance of an object"

    I would appreciate any feedback since I would love to use this really nice and compact code snippet to do screenshot capture, however I have to capture approximately 100-4000 Screenshots over the span of 60-120minutes.

    Any suggestions would be welcome.
    Sincerely
    Wow, that's a lot of screenshots, worst case scenario by my calculations means 1.1 screenies per second. That is probably pushing it a bit. The thing about printscreen is that it is not a high-priority feature. If you want to take many snaps, then you would be much better off using the API. You would have much better performance (you would probably be able to do 2 or 3 snaps per second, depending on how fast you can save the data). But it would be at the cost of complexity. API would be a little harder to code, but it's probably worth it.

    I don't have any samples for you at the moment, but the API functions you should check out are:

    GetDC
    BitBlt (The old favourite )

    If you have API-Guide installed you can get some examples off there.

    Hope that helps.

    PS< Can you post the code that caused your error?
    I don't live here any more.

  9. #9
    Frenzied Member FishGuy's Avatar
    Join Date
    Mar 2005
    Location
    Bradford UK
    Posts
    1,708

    Re: VB.NET - Screenshot to jpeg...

    I have looked at this thread and it seems that it could solve one of my problems but I need it to work as a windows service or at least in the background so the user is unaware it is running. the main problems seem to be caused by the send keys command and the IData objects not been recognised in services. Any Ideas.

  10. #10
    Frenzied Member FishGuy's Avatar
    Join Date
    Mar 2005
    Location
    Bradford UK
    Posts
    1,708

    Re: VB.NET - Screenshot to jpeg...

    Ok Ihave added a reference to system.windows.forms which has solved my Clipboard problems i think, I just need it to recognise image formats.

  11. #11
    Frenzied Member FishGuy's Avatar
    Join Date
    Mar 2005
    Location
    Bradford UK
    Posts
    1,708

    Re: VB.NET - Screenshot to jpeg...

    referencin system.drawing cleared some more errors but
    Code:
    Dim bmap As Bitmap
                If data.GetDataPresent(GetType(System.Drawing.Bitmap)) Then
                    bmap = CType(data.GetData(GetType(System.Drawing.Bitmap)), Bitmap)
                    bmap.Save("L:/DeskSpy/" & Now & ".jpg", Imaging.ImageFormat.Jpeg)
                End If
    Underlined in blue is Bitmap and Imaging _ Name Imaging is not declared and type Bitmap is not defined????????

  12. #12
    Frenzied Member FishGuy's Avatar
    Join Date
    Mar 2005
    Location
    Bradford UK
    Posts
    1,708

    Re: VB.NET - Screenshot to jpeg...

    Ok I have completed my transformation of it into a windows service - but it doesnt quite work, The service installs and starts but on debugging there is an error. That obeject reference not set to an instance of an object. line 86 (If data.GetDataPresent(GetType(System.Drawing.Bitmap)) Then) any suggestions please.
    Code:
    Option Strict Off
    Imports System.ServiceProcess
    Imports System.Timers
    Imports System.Windows.Forms
    Imports System.Drawing
    
    
    Public Class TimerService
        Inherits System.ServiceProcess.ServiceBase
    
    #Region " Component Designer generated code "
    
        Public Sub New()
            MyBase.New()
    
            ' This call is required by the Component Designer.
            InitializeComponent()
    
            ' Add any initialization after the InitializeComponent() call
    
        End Sub
    
        'UserService overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub
    
        ' The main entry point for the process
        <MTAThread()> _
        Shared Sub Main()
            Dim ServicesToRun() As System.ServiceProcess.ServiceBase
    
            ' More than one NT Service may run within the same process. To add
            ' another service to this process, change the following line to
            ' create a second service object. For example,
            '
            '   ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
            '
            ServicesToRun = New System.ServiceProcess.ServiceBase() {New TimerService()}
    
            System.ServiceProcess.ServiceBase.Run(ServicesToRun)
        End Sub
    
        'Required by the Component Designer
        Private components As System.ComponentModel.IContainer
    
        ' NOTE: The following procedure is required by the Component Designer
        ' It can be modified using the Component Designer.  
        ' Do not modify it using the code editor.
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            components = New System.ComponentModel.Container()
            Me.ServiceName = "TimerServiceTest"
        End Sub
    
    #End Region
    
        ' This fires every 10 seconds.
        Private WithEvents ServiceTimer As New System.Timers.Timer(10000)
        Private Counter As Integer
    
        Protected Overrides Sub OnStart(ByVal args() As String)
            ServiceTimer.Start()
        End Sub
    
        Protected Overrides Sub OnStop()
            ServiceTimer.Stop()
        End Sub
        Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)
        Private Const VK_SNAPSHOT As Short = &H2CS
        Private Sub DoWork(ByVal sender As Object, _
          ByVal e As ElapsedEventArgs) Handles ServiceTimer.Elapsed
            Counter += 1
            Debug.WriteLine("Repetition #" & Counter.ToString())
            Try
                Call keybd_event(System.Windows.Forms.Keys.Snapshot, 0, 0, 0)
                System.Threading.Thread.Sleep(200) ' To have time to catch the clipboard
    
                Dim data As IDataObject
                data = Clipboard.GetDataObject()
                Dim bmap As Bitmap
                If data.GetDataPresent(GetType(System.Drawing.Bitmap)) Then
                    bmap = CType(data.GetData(GetType(System.Drawing.Bitmap)), Bitmap)
                    bmap.Save("c:/SpyTest.jpg", Imaging.ImageFormat.Jpeg)
                End If
            Catch Err As Exception
                Debug.WriteLine(Err.ToString())
            End Try
        End Sub
    
    End Class

  13. #13
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Re: VB.NET - Screenshot to jpeg...

    FYI, I recently added screen-rectangle grabbing support to BlitterChip. See here, the attachment might be useful to you....
    http://www.vbforums.com/showpost.php...63&postcount=2
    I don't live here any more.

  14. #14
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Re: VB.NET - Screenshot to jpeg...

    Quote Originally Posted by FishGuy
    That obeject reference not set to an instance of an object. line 86 (If data.GetDataPresent(GetType(System.Drawing.Bitmap)) Then)
    Sounds like there was nothing on the clipboard.
    I don't live here any more.

  15. #15
    Frenzied Member FishGuy's Avatar
    Join Date
    Mar 2005
    Location
    Bradford UK
    Posts
    1,708

    Re: VB.NET - Screenshot to jpeg...

    I dont understand why not unless its simply because a service cannot properly invoke Call keybd_event(System.Windows.Forms.Keys.Snapshot, 0, 0, 0)

  16. #16
    Frenzied Member FishGuy's Avatar
    Join Date
    Mar 2005
    Location
    Bradford UK
    Posts
    1,708

    Re: VB.NET - Screenshot to jpeg...

    Wossname-
    I ditched all my old code and used your Blitterchip class, which worked just as i wanted as a windows app but not as a windows service. any idea why? It executes ok and does take a screen grab except the screen grab is just black.
    heres my code.
    VB Code:
    1. Option Strict On
    2. Imports System.ServiceProcess
    3. Imports System.Timers
    4. Imports System.Drawing
    5. Imports System.Windows.Forms
    6. Public Class TimerService
    7.     Inherits System.ServiceProcess.ServiceBase
    8.  
    9. #Region " Component Designer generated code "
    10.  
    11.     Public Sub New()
    12.         MyBase.New()
    13.  
    14.         ' This call is required by the Component Designer.
    15.         InitializeComponent()
    16.  
    17.         ' Add any initialization after the InitializeComponent() call
    18.  
    19.     End Sub
    20.  
    21.     'UserService overrides dispose to clean up the component list.
    22.     Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
    23.         If disposing Then
    24.             If Not (components Is Nothing) Then
    25.                 components.Dispose()
    26.             End If
    27.         End If
    28.         MyBase.Dispose(disposing)
    29.     End Sub
    30.  
    31.     ' The main entry point for the process
    32.     <MTAThread()> _
    33.     Shared Sub Main()
    34.         Dim ServicesToRun() As System.ServiceProcess.ServiceBase
    35.  
    36.         ' More than one NT Service may run within the same process. To add
    37.         ' another service to this process, change the following line to
    38.         ' create a second service object. For example,
    39.         '
    40.         '   ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
    41.         '
    42.         ServicesToRun = New System.ServiceProcess.ServiceBase() {New TimerService}
    43.  
    44.         System.ServiceProcess.ServiceBase.Run(ServicesToRun)
    45.     End Sub
    46.  
    47.     'Required by the Component Designer
    48.     Private components As System.ComponentModel.IContainer
    49.  
    50.     ' NOTE: The following procedure is required by the Component Designer
    51.     ' It can be modified using the Component Designer.  
    52.     ' Do not modify it using the code editor.
    53.     <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    54.         components = New System.ComponentModel.Container
    55.         Me.ServiceName = "TimerServiceTest"
    56.     End Sub
    57.  
    58. #End Region
    59.  
    60.     ' This fires every 10 seconds.
    61.     Private WithEvents ServiceTimer As New Timers.Timer(10000)
    62.     Private Counter As Integer
    63.  
    64.     Protected Overrides Sub OnStart(ByVal args() As String)
    65.         ServiceTimer.Start()
    66.     End Sub
    67.  
    68.     Protected Overrides Sub OnStop()
    69.         ServiceTimer.Stop()
    70.     End Sub
    71.     Private Sub DoWork(ByVal sender As Object, _
    72.    ByVal e As ElapsedEventArgs) Handles ServiceTimer.Elapsed
    73.         Counter += 1
    74.         Debug.WriteLine("Repetition #" & Counter.ToString())
    75.         Try
    76.             Dim i As Bitmap = BlitterChip.ScreenGrab(New Rectangle(0, 0, 1200, 800))
    77.             i.Save("c:/SpyTest1.jpg", Imaging.ImageFormat.Jpeg)
    78.         Catch Err As Exception
    79.             Debug.WriteLine(Err.ToString())
    80.         End Try
    81.     End Sub
    82.  
    83. End Class

  17. #17
    l33t! MrPolite's Avatar
    Join Date
    Sep 2001
    Posts
    4,428

    Re: VB.NET - Screenshot to jpeg...

    with all due respect it's alightly stupid to get a screenshot using print screen. You ruin the guy's clipboard data too I found this a few days before and it's in C# http://www.developerfusion.com/show/4630/
    that gets the screen using APIs, I'm sure some of you gurus can rewrite that in VB
    rate my posts if they help ya!
    Extract thumbnail without reading the whole image file: (C# - VB)
    Apply texture to bitmaps: (C# - VB)
    Extended console library: (VB)
    Save JPEG with a certain quality (image compression): (C# - VB )
    VB.NET to C# conversion tips!!

  18. #18
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Re: VB.NET - Screenshot to jpeg...

    Quote Originally Posted by MrPolite
    with all due respect it's alightly stupid to get a screenshot using print screen. You ruin the guy's clipboard data too I found this a few days before and it's in C# http://www.developerfusion.com/show/4630/
    that gets the screen using APIs, I'm sure some of you gurus can rewrite that in VB
    Yes it is stupid. You should read post #16 API all the way baby, yeah!

    That code on Developerfusion is a bit flabby imho. Why use 300 api functions when 2 will do? Blitterchip bungs the image straight into a bitmap for you so you can save it in any format supported by GDI+.

    I don't live here any more.

  19. #19
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Re: VB.NET - Screenshot to jpeg...

    Quote Originally Posted by FishGuy
    Wossname-
    I ditched all my old code and used your Blitterchip class, which worked just as i wanted as a windows app but not as a windows service. any idea why? It executes ok and does take a screen grab except the screen grab is just black.
    You code looks OK to me. I wonder if Services are unable to query video memory? I have limited Services experience so I don't really know what to do about that, sorry.
    I don't live here any more.

  20. #20
    l33t! MrPolite's Avatar
    Join Date
    Sep 2001
    Posts
    4,428

    Re: VB.NET - Screenshot to jpeg...

    yeah I see it now. All your API are belong to me
    umm one thing though, you are using GetDC(0) to get the desktop dc? is that a legitimate way of doing it?
    would that always work?
    rate my posts if they help ya!
    Extract thumbnail without reading the whole image file: (C# - VB)
    Apply texture to bitmaps: (C# - VB)
    Extended console library: (VB)
    Save JPEG with a certain quality (image compression): (C# - VB )
    VB.NET to C# conversion tips!!

  21. #21
    PowerPoster abhijit's Avatar
    Join Date
    Jun 1999
    Location
    Chit Chat Forum.
    Posts
    3,226

    Re: VB.NET - Screenshot to jpeg...

    I got a problem with the code posted by wossname. I found that it only captured a corner of the screen. Could someone take a look? Help
    Everything that has a computer in will fail. Everything in your life, from a watch to a car to, you know, a radio, to an iPhone, it will fail if it has a computer in it. They should kill the people who made those things.- 'Woz'
    save a blobFileStreamDataTable To Text Filemy blog

  22. #22

    Thread Starter
    Hyperactive Member Libero's Avatar
    Join Date
    Jun 2000
    Location
    Swedish viking
    Posts
    460

    Re: VB.NET - Screenshot to jpeg...

    Thx for hijacking

  23. #23
    PowerPoster abhijit's Avatar
    Join Date
    Jun 1999
    Location
    Chit Chat Forum.
    Posts
    3,226

    Re: VB.NET - Screenshot to jpeg...

    Oh, so it was your code then. How do I capture the whole screen?
    Everything that has a computer in will fail. Everything in your life, from a watch to a car to, you know, a radio, to an iPhone, it will fail if it has a computer in it. They should kill the people who made those things.- 'Woz'
    save a blobFileStreamDataTable To Text Filemy blog

  24. #24

    Thread Starter
    Hyperactive Member Libero's Avatar
    Join Date
    Jun 2000
    Location
    Swedish viking
    Posts
    460

    Re: VB.NET - Screenshot to jpeg...

    Quote Originally Posted by abhijit
    Oh, so it was your code then. How do I capture the whole screen?
    I mean hijacking the thread

    And as far as i remember, the code i posted capture the whole screen. (havent been programming for a while)

  25. #25
    PowerPoster abhijit's Avatar
    Join Date
    Jun 1999
    Location
    Chit Chat Forum.
    Posts
    3,226

    Re: VB.NET - Screenshot to jpeg...

    Oh I am sorry about that, but I still can't get this code to work properly.
    Everything that has a computer in will fail. Everything in your life, from a watch to a car to, you know, a radio, to an iPhone, it will fail if it has a computer in it. They should kill the people who made those things.- 'Woz'
    save a blobFileStreamDataTable To Text Filemy blog

  26. #26
    Frenzied Member conipto's Avatar
    Join Date
    Jun 2005
    Location
    Chicago
    Posts
    1,175

    Re: VB.NET - Screenshot to jpeg...

    Quote Originally Posted by MrPolite
    with all due respect it's alightly stupid to get a screenshot using print screen. You ruin the guy's clipboard data too I found this a few days before and it's in C# http://www.developerfusion.com/show/4630/
    that gets the screen using APIs, I'm sure some of you gurus can rewrite that in VB
    Can't you just back up the clipboard data then replace it when you're done?

    Bill
    Hate Adobe Acrobat? My Codebank Sumbissions - Easy CodeDom Expression evaluator: (VB / C# ) -- C# Scrolling Text Display

    I Like to code when drunk. Don't say you weren't warned.

  27. #27
    l33t! MrPolite's Avatar
    Join Date
    Sep 2001
    Posts
    4,428

    Re: VB.NET - Screenshot to jpeg...

    Quote Originally Posted by conipto
    Can't you just back up the clipboard data then replace it when you're done?

    Bill
    yeah sure
    but when you can get the screenshots using apis, why not just do that instaed
    rate my posts if they help ya!
    Extract thumbnail without reading the whole image file: (C# - VB)
    Apply texture to bitmaps: (C# - VB)
    Extended console library: (VB)
    Save JPEG with a certain quality (image compression): (C# - VB )
    VB.NET to C# conversion tips!!

  28. #28
    Frenzied Member conipto's Avatar
    Join Date
    Jun 2005
    Location
    Chicago
    Posts
    1,175

    Re: VB.NET - Screenshot to jpeg...

    Quote Originally Posted by MrPolite
    yeah sure
    but when you can get the screenshots using apis, why not just do that instaed

    Well, MS seems to think .NET users should be avoiding API calls.. and seems to be hinting around at their planned obsolesence...

    Bill
    Hate Adobe Acrobat? My Codebank Sumbissions - Easy CodeDom Expression evaluator: (VB / C# ) -- C# Scrolling Text Display

    I Like to code when drunk. Don't say you weren't warned.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width