Why does GetPixel stop working in my program?

Hi All
I have a strange problem. I am using GetPixel to perform a screen scrape which takes about half an hour to get all the data I need once a week. At least it WOULD take half an hour if it ever finished! It always crashes after about 20 minutes, but I can then
restart from the point of the crash and it completes fine.
Here is my code:
Do
lColor = GetPixel(DC, x, y)
If lColor >= 0 Then Exit Do
DC = GetDC(0)
Loop
I know that GetPixel / DC can sometimes drop out and return -1 hence the above loop, but it seems that after about 8 million calls (about 20 minutes in my program) it just starts returning zero every single time. This causes an exception elsewhere in my program
but the underlying problem is GetPixel returning zero. I have watched this happen on several occasions now and the pixels being interrogated are most definitely not black and the screensaver has not come on ar anything like that.
Does anybody have any ideas why this might be happening and more importantly, how I can fix it?
Many thanks
Rich

Can I ask you if you are getting more than one pixel -at a time-? If you are, then I have some good news for you, you can do this considerably faster if you were to use BitMap.Lockbits. The reason being that each time you call the GetPixel method, internally
lockbits gets called to first lock the resource, and then again to unlock it, all for a single GetPixel operation. Implementing your own routine to gather pixels can be considerably faster, but admittedly more difficult. Below the following example will show
you how to get large collections of pixels with a single call to Bitmap.Lock, and Bitmap.Unlock, which will DRASTICALLY increase your overall performance. Please be advised that this example only supports 32 bit per pixel images, and if you wish to add support,
you would have to first understand how this works.
Example:
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PictureBox1.Width = 101
PictureBox1.Height = 101
Dim bmp As New Bitmap(PictureBox1.Width, PictureBox1.Height)
Dim g As Graphics = Graphics.FromImage(bmp)
Dim rTopLeft As New Rectangle(0, 0, 50, 50)
Dim rTopRight As New Rectangle(50, 0, 50, 50)
Dim rBottomLeft As New Rectangle(0, 50, 50, 50)
Dim rBottomRight As New Rectangle(50, 50, 50, 50)
g.FillRectangle(Brushes.Red, rTopLeft)
g.FillRectangle(Brushes.Blue, rTopRight)
g.FillRectangle(Brushes.Yellow, rBottomLeft)
g.FillRectangle(Brushes.Green, rBottomRight)
PictureBox1.Image = bmp
Dim getPixel1 As New Point(0, 0)
Dim getPixel2 As New Point(50, 0)
Dim getPixel3 As New Point(0, 50)
Dim getPixel4 As New Point(50, 50)
Dim pixelsToGet As New List(Of Point)
pixelsToGet.Add(getPixel1)
pixelsToGet.Add(getPixel2)
pixelsToGet.Add(getPixel3)
pixelsToGet.Add(getPixel4)
Dim pixels As List(Of Pixel) = GetPixels(pixelsToGet, bmp)
pbPix1.BackColor = pixels(0).Color
pbPix2.BackColor = pixels(1).Color
pbPix3.BackColor = pixels(2).Color
pbPix4.BackColor = pixels(3).Color
End Sub
Function GetPixels(pixelsToGet As List(Of Point), source As Bitmap) As List(Of Pixel)
Dim results As New List(Of Pixel)
Dim sourceRect As New Rectangle(0, 0, source.Width - 1, source.Height - 1)
Dim bmd As System.Drawing.Imaging.BitmapData = _
source.LockBits(sourceRect, Imaging.ImageLockMode.ReadOnly, source.PixelFormat)
Dim ptr As IntPtr = bmd.Scan0
Dim bytes As Integer = Math.Abs(bmd.Stride) * bmd.Height
Dim allPixelBytes(bytes - 1) As Byte
System.Runtime.InteropServices.Marshal.Copy(ptr, allPixelBytes, 0, bytes)
Dim bytesPerPixel As Integer = 0
Select Case bmd.PixelFormat
Case Imaging.PixelFormat.Format32bppArgb
bytesPerPixel = 4
Case Else
Throw New NotImplementedException("Currently only 32bits per pixel is supported!")
End Select
For currentIndex As Integer = 0 To allPixelBytes.Count - 1 Step bytesPerPixel
Select Case bmd.PixelFormat
Case Imaging.PixelFormat.Format32bppArgb
For Each Loc As Point In pixelsToGet
If PixelLocationToIndex(Loc, bmd.PixelFormat, source.Width) = currentIndex Then
Dim blueComponent As Byte = allPixelBytes(currentIndex)
Dim greenComponent As Byte = allPixelBytes(currentIndex + 1)
Dim redComponent As Byte = allPixelBytes(currentIndex + 2)
Dim alphaComponent As Byte = allPixelBytes(currentIndex + 3)
Dim pixelColor As Color = Color.FromArgb(alphaComponent, redComponent, greenComponent, blueComponent)
Dim pixel As New Pixel(Loc, pixelColor)
results.Add(pixel)
End If
Next
Case Else
Throw New NotImplementedException("Currently only 32bits per pixel is supported!")
End Select
Next
source.UnlockBits(bmd)
Return results
End Function
Public Function PixelLocationToIndex(loc As Point, pixelFormat As System.Drawing.Imaging.PixelFormat, bitmapWidth As Integer) As Integer
Dim bytesPerPixel As Integer = 0
Select Case pixelFormat
Case Imaging.PixelFormat.Format32bppArgb : bytesPerPixel = 4
Case Else : Throw New NotImplementedException("Currently only 32bits per pixel is supported!")
End Select
Dim bytesPerRowOfPixel As Integer = bytesPerPixel * bitmapWidth
Dim yPixels As Integer = bytesPerRowOfPixel * loc.Y
Dim xPixels As Integer = bytesPerPixel * loc.X
Return xPixels + yPixels
End Function
Class Pixel
Public Property Location As Point
Public Property Color As Color
Sub New(location As Point, color As Color)
Me.Location = location
Me.Color = color
End Sub
End Class
End Class
“If you want something you've never had, you need to do something you've never done.”
Don't forget to mark
helpful posts and answers
! Answer an interesting question? Write a
new article
about it! My Articles
*This post does not reflect the opinion of Microsoft, or its employees.

Similar Messages

  • Why does mail stop working?

    Why does mail stop working when it has worked fine for years?

    OK, thank you.  I use apple for e-mail.  I have an @me address and I have long subscribed to mobile me, which has recently become icloud.  Yesterday the @me mail account appeared to stop recognizing my e-mail password for my primary mail account on my two imacs but not on my ipad.  The most recent e-mail I have received on my imacs is 7:16am yesterday, but I know from my ipad that I have received numerous e-mails since then.  I have other mail accounts, including one for the school where I teach.  I am receiving e-mail on the school account ok.
    I made no changes to my password or otherwise for my primary mail account any time recently.  I also still have my @mac address.
    Generally, I do not understand icloud.  I do not understand how to sync information across computers.
    When I go to preferences in mail and I click and accounts and account information, I do not understand anything that I see there.  When I try to re-type my password, there seems to be no way to save it except to switch to another mail account.  I know from past experience that if I attempt to fix whatever might be wrong with mail I do not know what I am doing.
    Any information would be helpful.  Thank you.

  • Why does Itunes stop working when I start to play a movie

    Why does Itunes stop working when I start to play a preview or watch a downloaded movie rental

    Let's try the following user tip with that one:
    iTunes for Windows 10.7.0.21: "iTunes has stopped working" error messages when playing videos, video podcasts, movies and TV shows

  • Why does ServerSocket stop working after some time?

    Hi to all.
    I have a following problem:
    I wrote a multithread application that uses sockets ( TCP ), and use it to transfer some objects between computers in VPN.
    It all works just fine, except that sometimes my server socket ( implemented as a separate Thread ) just stops working, and other computers cannot connect to it...?
    I didn't specify setSOTimeout(), and did all Exception catch-ing in the thread.
    Today, I had some >50000 connections in about 5 hours, and than it just stopped! My server socket stopped accepting any connections...
    I restarted my application, and everything worked again properly...
    Does anybody know why is this happening?
    Please, any suggestion is appreciated....
    Thank you.

    Hi, thank you all for answering me.
    @baftos:
    I didn't specify any backlog parameter value. 50 connections at a time seems more than enough for this application... ( Are you sure that 50 is the default value )
    I never have more than about 40 connections simultaneously opened, and yes - each one is a separate thread.
    @dannyyates:
    You're rights, I should have provided some code.
    Here it is:
    public class Server implements Runnable
    ServerSocket serversocket = null;
    Socket clientSocket = null;
    continueWorking boolean = true;
        public void run()
                startServer(); 
        public void startServer()
            try
                 serversocket = new ServerSocket(3344);
            catch (IOException e)
                 System.out.println(e.getMessage());  
         while ( continueWorking==true )
             try
                  clientSocket = serversocket.accept();
                  Worker Worker = new Worker(clientSocket);
                  new Thread(Worker).start();
             catch (IOException e)
                  System.out.println(e.getMessage());
            System.out.println("The server is shutting down...");
    class Worker implements Runnable
        ObjectInputStream obj;
        Socket clientSocket;
        public Worker(Socket clientSocket)
             this.clientSocket = clientSocket;
            try
              obj = new ObjectInputStream(clientSocket.getInputStream());
             catch (IOException e)
                  System.out.println(e.getMessage());
        public void run()
            Object object;
         try {
                          try
                               object=(Object)obj.readObject();
                                                   // do something with object....
                          catch (ClassNotFoundException e)
                               System.out.println(e.getMessage());
                        catch (Exception e)
                obj.close();
                clientSocket.close();
         catch (IOException e)
        catch (Exception e)
        }What I don't like here is the constructor of the Worker. Could this block the server?
    Edited by: Darko on Apr 7, 2009 11:24 PM

  • Why does Cmd+\ stop working?

    I've been having trouble where a keyboard shortcut in an app - Cmd+\ - gets not response. Or rather it does work on first booting but at some point it stops working. The first thought was another app was grabbing the shortcut association, but I can't find any sign of that.
    By chance, with the keyboard viewer left open, I noticed that on initial boot the viewer registers both the Cmd and \ keypresses. When the shortcut stops working, the viewer shows - for the same keypress combo - that only the Cmd key is registered as down in the viewer. Interesting!
    This is happening on a Sping 2011 unibody MacBookPro (v8,2, Core i7 2.2GHz, 8 Gb RAM, not under heavy load). I have an external extended keyboard (for numberpad use) usually attached via the USB port on an external Apple 27" display. Anyway, the change in key registration is the same in the keyboard viewer whether I use the external keyboard (also if plugged directly into the MBP's USB  port) or the MacBook Pro's own keypad.
    Uaccessibility settings were mooted as a cause. Checking, I've  'enable access for assitive devices' and screen zoom set 'on'. Disabling either/both of these has no effect.
    Both Cmd and \ keys work fine on their own.
    Might this be a hardware fault or am I somehow triggering some obscure setting.

    Good spot. Yes, it does turn out to be 1Password, in a roundabout way. Odd how that shortcut didn't show up even in things like KeyCue, but it is a shortcut for a Safari Extension so may be less 'visibile' to shortcut-sniffing utilities than normal apps.
    Acting on your tip, I visisted 1Password and got to here: http://help.agilebits.com/1Password3/keyboard_shortcuts.html. I nixed their 'Fill Login' shortcut - which thankfully I don't use. After that Tinderbox worked well.
    The shortcut is set via 1Password's setting and  - I think - affects the plug-in is all browsers (or if used only work with Safari). I have the 1P extension in Safari/Firefox/Chrome here having altered the 1P preferences all seems well.
    The really weird bit was how, when running, the iP extension shortcut suppressed the '\' in a 'Cmd+\' keypress. Very odd.
    FWIW, I stumbled on this as I also use Eastgate's Tinderbox daily and that has Cmd+\ hard mapped to a much-used dialog. the only possible fix short of not using one app or the other was to remove or alter the shortcut for the 1P browser extension.
    Thanks again,
    Mark

  • Why does shockwave stop working and my entire computer freeze??

    my firefox page freezes then a box opens that says shockwave has stopped working would you like to continue i say yes it stays frozen then opens again asking the same question so i hit no and it works for a little while then does it all again, i've updated my shockwave a few different times. still having the same issue.

    Please post a screen shot of the dialog box here. I'll bet any money that it cites "Shockwave Flash", in which case you should search for, and then post again if you still need to, on a forum for the Flash Player

  • Why does Siri stop working, or become unavailable?

    The topic says it all. Why is it that sometimes, even in a 4G area, Siri suddenly doesn't  work?

    There are a few reasons why siri will stop listening:
    1. It is having problems connecting to the network so can't search for what you are looking for. You are prompted with something like: I am sorry I can't connect right now.
    2. There is a pause when you are dictating something to siri so it assumes you are done. Pauses of about 2 or 3 seconds should do it.
    3. You accidentally press the siri button indicating you are done dictating to siri.
    If none of these are the problem, I don't know what else to do. How often is this occuring?

  • Using PP CC and Encore CS6 why does Encore stop working after I select open/create project?

    When I go into open an existing project it will me in, but when trying to create a new project, it will act as if it will open and then comes up with the error box "access denied or enocre has stopped working Windows is collecting information about the issue this may take a few moments, and Windows will close the program.

    These questions below may be for a different product... but the KIND of information you need to supply is the same, for the products you use
    More information needed for someone to help... please click below and provide the requested information
    -Premiere Pro Video Editing Information FAQ http://forums.adobe.com/message/4200840

  • Why does iTunes stop working when trying to connect to the iTunes Store on PC

    Everytime I try to go into the iTunes Store on my Windows 7 PC I get a popup that says "iTunes has stopped working, Windows will try to find a solution to the problem."
    I wonder why this is happening and I just updated to the new iTunes version about 10 minutes ago (I had this issue with the previous version too.) What do I do?

    I don't believe it's just you. I am having an issue with iTunes myself on both my iMac and MacBook Pro. The iTunes store won't load as far as viewing my account info or trying to download previous purchases.

  • Why does itunes stop working when I try to watch videos

    When I try to watch videos on my pc and itunes stop working.  Why is this happening?

    Try the following user tip:
    iTunes for Windows 10.7.0.21: "iTunes has stopped working" error messages when playing videos, video podcasts, movies and TV shows

  • Why does iTunes stop working when I click on the menu bar?

    Whenever I click the grey menu bar (artists, genre, videos, playlists, match, etc) iTunes stops working and Windows has a pop up that says it's closing. I tried updating to 11.4... but then itunes says it is missing a file or something like that and will not open period so I have to use a system restore to get it back..I;ve been enduring this without editng playlists and etc for a few months now. Please help? Thank you for any input.

    this is for the benefit of putting video effects on my iMovie projects, which I cannot import videos for my video app

  • Why does cs5 stop working when printing

    At my wits end...CS6 continually Stops working when I attempt to print to a Ricoh printer...all ok before upgrade from XP...drivers appear ok and have been reloaded.

    Which one is it?  Title of your post says CS5, body of message says CS6.
    If you give complete and detailed information about your setup and the issue at hand, such as your platform (Mac or Win), exact versions of your OS, of Photoshop and of Bridge, machine specs, what troubleshooting steps you have taken so far, what error message(s) you receive, if having issues opening raw files also the exact camera make and model that generated them, etc., someone may be able to help you.
    Please read this FAQ for advice on how to ask your questions correctly for quicker and better answers:
    http://forums.adobe.com/thread/419981?tstart=0
    Thanks!

  • TS1717 why does itunes stop working when i connect my ipad to my computer

    my itunes stops working only when my ipad is connected to my computer but if my iphone is connected it works fine
    here are the crash logs
    Problem signature:
      Problem Event Name:          BEX
      Application Name:          iTunes.exe
      Application Version:          10.7.0.21
      Application Timestamp:          504d85d9
      Fault Module Name:          StackHash_f304
      Fault Module Version:          0.0.0.0
      Fault Module Timestamp:          00000000
      Exception Offset:          PCH_2E_FROM_ntdll+0x00041318
      Exception Code:          c0000005
      Exception Data:          00000008
      OS Version:          6.2.9200.2.0.0.256.48
      Locale ID:          1033
      Additional Information 1:          f304
      Additional Information 2:          f304717eeed43189b7c0d7c053f4a949
      Additional Information 3:          91cd
      Additional Information 4:          91cd4b3c15f583528765b320b84bda47

    Hi Eddie A.,
    Welcome to the Apple Support Communities!
    I understand that iTunes is becoming unresponsive when you connect your iPhone. In this situation, I would recommend the steps in the following article to isolate and resolve this situation.
    iTunes: May become unresponsive when connecting iPhone, iPad, or iPod touch
    http://support.apple.com/kb/ts3219
    I hope this helps,   
    -Joe

  • Why does itunes stop working when trying to play videos?

    Itunes gets a microsoft message that it has stopped working and gets a black screen and shuts down itunes.

    Try the following user tip:
    iTunes for Windows 10.7.0.21: "iTunes has stopped working" error messages when playing videos, video podcasts, movies and TV shows

  • BEX64 - Why does CS4 stop working when using Vanishing Point?

    While using the Vanishing Point in CS4 64 bit, Photoshop shuts down when I attempt to move text or move a plane within a grid.
    Does anyone know how to stop the crashes?
    I am using a Toshiba PC, Windows 7, I7 processor and 4 gigs of memory.
    I have attempted to solve the problem by doing the following but they have not worked:
    I expanded Photoshops memory usage to 90%.
    I have updated all of the critical Windows 7 updates.
    I have updated Photoshop CSR to 11.0.2
    I have received different Problem Event Names.  They are:
    BEX64
    APPCRASH
    Details of my first BEX64 crash were:
    Application Name:  Photoshop.exe
    Application Timestamp: 48d38aa7
    Fault Module Name: image_flow.dll
    Fault Module Version: 1.0.0.1
      Exception Offset:           000000000001a06a
      Exception Code:             c0000409
      Exception Data:              0000000000000000
    1 OS Version:      6.1.7600.2.0.0.768.3
      Locale ID:           1033
    Additional Information 1:             10f0
      Additional Information 2:           10f0d4ac53e068c0db93784baaf90d6f
      Additional Information 3:           29f3
      Additional Information 4:           29f3a8d1a654618fbfcedb430e6c7a63plication: 11.0.0.0
    Video Card Driver: nvd3dumx.dll,nvwgf2umx.dll,nvwgf2umx.dll,nvd3dum,nvwgf2um,nvwgf2um
    Driver Version: 8.16.11.8829
    Built-in memory: 4031 MB
    Free memory: 2072 MB
    Memory available to Photoshop: 3404 MB
    Memory used by Photoshop: 60 %
    Photoshop scratch has async I/O enabled
    Scratch volume(s):
      Startup, 453.9G, 278.5G free
    Primary Plug-ins folder: C:\Program Files\Adobe\Adobe Photoshop CS4 (64 Bit)\Plug-ins\
    Additional Plug-ins folder: not set
    Thanks in advance for any help you can offerBreeze 3

    Hello Dec9,
    Thanks for the response.
    I installed the 11.0.2 update and I still have teh BEX64 crash.  I have also tried starting PS CS4 and pressed Cntrl Shift & Alt at the same time.  It still crashes when I get to the point of moving text or a plane in a grid within Vanishing Point.
    I also backed off from 90% as you suggested.
    My latest problem details are as follows:
    Problem Event Name:                          BEX64
      Application Name:                             Photoshop.exe
      Application Version:                           11.0.2.0
      Application Timestamp:     4bf2d91c
    Fault Module Name:                            StackHash_56f5
      Fault Module Version:                        0.0.0.0
      Fault Module Timestamp:                  00000000
      Exception Offset:                                0000000000000000
      Exception Code:                                  c0000005
      Exception Data:                                   0000000000000008
      OS Version:                                          6.1.7600.2.0.0.768.3
      Locale ID:                                             1033
      Additional Information 1:                  56f5
      Additional Information 2:                  56f50057683cdbfd654c11c2adb3bbee
      Additional Information 3:                  11e5
      Additional Information 4:  11e55f3ceaa742af752d4088e4931316

Maybe you are looking for

  • Itunes doesn't save any of my songs after I exit it!

    My ipod is fine, all my playlist and songs are still there but on my laptop, everything is gone. When I added all my songs again and sync my ipod to it, all the songs show up but the info on my ipod doesn't show up. And as soon as I finish adding my

  • EXS samples in Project Folder...

    When I tell Logic to copy my samples to the project folder (using the Assets section of the Project Settings), is Logic still using the samples from their original location during playback, or is it now playing the files from my Project Folder? I'm h

  • User Profiles property as search refiners

    SharePoint Online: I have a requirement to refine people search results based on sills. We want to sue the default property SKILLS. I confirmed the property is available but is set as not refinable. We are trying to setup a managed property using the

  • Nikon D7000 .nef files

    I have a Nikon D7000 camera which creates raw files - .nef and my version of CS5 is not able to open them directly. Does the latest version of CS5 resolve this problem?

  • Cursor issues in Word and Outlook after Adobe 9 pro trial download - any advice  - really annoying!

    Hi, have downloaded Adobe Professional 9 as a trial and am looking to buy it (work with a charity). Did use Foxit phantom Pro and had no issues much considering its a cheap copy, but had to change to adobe so it was compatible with a colleagues syste