You forgot the call to ReleaseDC(). You might just have created a huge memory leak. And what on earth are you trying to pass on as a hWnd? That's the ID (window handle) of the control/window you're trying to access, so try to get a valid value. If you want to access the desktop as a window, you can use the GetDesktopWindow() API call, which will return the hWnd of the mother of all windows, the desktop. You can proceed from there. These are the additional/changed code snippets:
#Private Declare Function ReleaseDC Lib "user32" (ByVal hWnd As Long,
+ByVal hDC As Long) As Long
Win32::API->Import(
'user32', 'long ReleaseDC(long hWnd, long hDC)',
);
#Private Declare Function GetDesktopWindow Lib "user32" () As Long
Win32::API->Import(
'user32', 'long GetDesktopWindow()',
);
sub PixelColor {
my ($hwnd, $x, $y) = @_;
my $dc = GetDC($hwnd);
my $rgb = GetPixel($dc, $x, $y);
ReleaseDC($hwnd, $dc);
return $rgb < 0 ? undef: sprintf "%06x", $rgb;
}
print PixelColor(GetDesktopWindow(), 100, 100);
Well, that's the theory. In practice I always get
"ffffff" undef back, which means this pixel can't be read — likely because the pixel data isn't buffered. Oh well. Perhaps it works better with a hWnd of an actual window...
p.s. This hWnd should be a property of your control or canvas, or whatever terminology you might be used to.
p.p.s. For people who feel like trying this out, make sure you have at least version 0.40 of Win32::API, or you'll get a deep recursion error on the Import method — something to do with AUTOLOAD, because that method doesn't exist. Needless to say, it won't work, either.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.