Custom trackbar ticks - winapi

I'm using the stock Trackbar control. I would like to custom draw the ticks.
Here I made an experiment, just trying to draw in the right place:
case WM_NOTIFY:
{
NMHDR* nMhdr = (NMHDR*) lParam;
NMCUSTOMDRAW* nMcd = (NMCUSTOMDRAW*) lParam;
if (nMhdr->code == NM_CUSTOMDRAW)
{
switch (nMcd->dwDrawStage)
{
case CDDS_PREPAINT:
{
return CDRF_NOTIFYITEMDRAW;
}
case CDDS_ITEMPREPAINT:
{
if (nMcd->dwItemSpec == TBCD_TICS)
{
FillRect(nMcd->hdc, &nMcd->rc, (HBRUSH) GetStockObject(BLACK_BRUSH));
return CDRF_SKIPDEFAULT;
}
else
{
return CDRF_DODEFAULT;
}
break;
}
default:
{
result = CDRF_DODEFAULT;
break;
}
}
}
break;
}
In my CDDS_ITEMPREPAINT, if dwItemSpec == TBCD_TICS, then the update rect (NMCUSTOMDRAW->rc) is always an empty rect. I checked, and for the other items (TBCD_CHANNEL and TBCD_THUMB), I get a valid rect and can draw in place of the channel and thumb.
Ok: so what's the point of TBCD_TICS if it doesn't give me a rect to draw in?
So maybe I can get the tick positions another way. Well, there's TBM_GETTICPOS, which seems like it would work. Except the documentation mentions this:
The positions of the first and last tick marks are not directly available via this message.
So how can I get the first and last tick positions? They do not correspond with the start and end of the channel, the ticks are inset slightly. Perhaps we can calculate the insert from the sides of the channel, but that seems fragile (especially on differently scaled displays).

So how can I get the first and last tick positions?
The old method (XP and older) to get them seems to still work (I just tested on Windows 10) :
RECT rectTrackbar;
GetClientRect(hWndTB, &rectTrackbar);
RECT rectThumb;
SendMessage(hWndTB, TBM_GETTHUMBRECT, 0, (LPARAM)&rectThumb);
int nThumbWidth = rectThumb.right - rectThumb.left;
int nXTicFirst = rectTrackbar.left += (nThumbWidth + 2);
int nXTicLast = rectTrackbar.right -= (nThumbWidth + 2 + 1);

Related

RestoreCapture FMX - Win32

I took this example of subclassing a Form's HWND as a starting point and then added in jrohde's code from from here that is designed to let you drag a Form by clicking anywhere on it (not on the caption bar). This code fails on the ReleaseCapture()line with this message: E2283 Use . or -> to call '_fastcall TCommonCustomForm::ReleaseCapture()
If i comment that line out the code runs and i can move the form by left mouse don and drag, but i can't let go of it. The mouse gets stuck to the form like flypaper. If i replace the ReleaseCapture() with a ShowMessage i can break out but that is obviously not the way to go...
What do i need to do allow that RestoreCapture() to run? This is Win32 app.
BELOW IS THE CODE i added to the original switch(uMsg) block:
// two int's defined above the switch statement
static int xClick;
static int yClick;
// new case added to the switch
case WM_LBUTTONDOWN:
SetCapture(hWnd);
xClick = LOWORD(lParam);
yClick = HIWORD(lParam);
break;
case WM_LBUTTONUP:
//ReleaseCapture(); // This is the problem spot <------------------------
ShowMessage("Up");
break;
case WM_MOUSEMOVE:
{
if (GetCapture() == hWnd) //Check if this window has mouse input
{
RECT rcWindow;
GetWindowRect(hWnd,&rcWindow);
int xMouse = LOWORD(lParam);
int yMouse = HIWORD(lParam);
int xWindow = rcWindow.left + xMouse - xClick;
int yWindow = rcWindow.top + yMouse - yClick;
SetWindowPos(hWnd,NULL,xWindow,yWindow,0,0,SWP_NOSIZE|SWP_NOZORDER);
}
break;
thanks, russ
From the error message you can derive that the compiler resolves the function ReleaseCapture() to TCommonCustomForm::ReleaseCapture(). But you want to call the Win32 API function ReleaseCapture(). Use ::ReleaseCapture(); instead of ReleaseCapture(); to enforce this.

PrintWindow: screenshot is offset sometimes

I'm taking screenshots of windows using PrintWindow(). This works finde with the following code.
This works most of the time - I'm calling it very often in a continuos loop - but sometimes it fails. I started saving screenshots of the times it fails. Sometimes they are just black, but sometimes the ClientArea of the captured window is somehow offset and only visible on half the picture. Why is that the case?
EDIT:
Is the PrintWindow function guaranteed to work, even when its called ~100times a second? What makes me wonder is, that after every print window I'm actually verifying two pixels which default colors I stored as a COLORREF at startup. The program says they match almost all the time. Still, once I use GetPixel, the returned value from other pixels is simply black or white from time to time (which should never be the case). Once I save the HDC/HBITMAP as a screenshot (I called GdiFlush before), the screenshot is just plain black (which shouldn't be the case either, as I said, I checked two pixels before...).
Well for now, back to the initial question: Is this definitely my fault, or is it possible that PrintWindow just gives random results from time to time, without returning an error?
Ok, this is the NEW CODE:
/* Try printing the window 10times, in case it fails. */
for (int i = 0; i <= NUM_ITERATIONS_PREP; i++) {
releaseSurface();
prepared_HWND = hwnd;
window_dc = GetWindowDC(hwnd);
surface = CreateCompatibleDC(window_dc);
if (surface) {
RECT r;
GetWindowRect(hwnd, &r);
bmp = CreateCompatibleBitmap(window_dc, r.right - r.left, r.bottom - r.top);
if (!ReleaseDC(hwnd, window_dc)) {
writeLog("ReleaseDC failed.", black, true);
}
if (bmp) {
old_surface_bmp = SelectBitmap(surface, bmp);
//InvalidateRect(hwnd, 0, TRUE);
//UpdateWindow(hwnd);
int result = PrintWindow(hwnd, surface, 0);
if (result != 0) {
if (!verify || verifySurface())
break;
else {
writeLog("Surface could not be verified on iteration " + std::to_string(i) + ". Saving screenshot.", black, true);
saveDebugScreenshot();
QThread::msleep(2);
}
} else {
writeLog("PrintWindow() failed.", black, true);
}
}
else {
writeLog("BMP creation failed.", black, true);
}
}
else {
writeLog("HDC creation failed.", black, true);
}
}
And the new RELEASE CODE:
/* If you call prepareSurface(), call this once the surface isn't need anymore. */
void ClientProfile::releaseSurface() {
SelectObject(surface, old_surface_bmp);
DeleteDC(surface);
DeleteObject(bmp);
prepared_HWND = NULL;
}
releaseSurface() is called either at the beginning of prepareSurface() and additionally every time I'm done processing a table (this means its called once too often for every prepareSurface(). Is that a problem?).
Oh and old_surface_bmp, bmp and surface are declared as private class attributes.

Allegro 5 detects long key press as several key presses

In the code block below I am trying to move a rectangle once for every key-press but the rectangle moves as long as I hold down a key.
ALLEGRO_EVENT ev;
while(!done)
{
al_wait_for_event(event_queue, &ev);
if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
{
switch(ev.keyboard.keycode)
{
case ALLEGRO_KEY_UP:
pos_y -= 10;
break;
case ALLEGRO_KEY_DOWN:
pos_y += 10;
break;
case ALLEGRO_KEY_RIGHT:
pos_x += 10;
break;
case ALLEGRO_KEY_LEFT:
pos_x -= 10;
break;
}
}
else if(ev.type == ALLEGRO_EVENT_KEY_UP)
{
if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
done = true;
}
al_draw_filled_rectangle(pos_x, pos_y, pos_x + 30, pos_y + 30, al_map_rgb(255,0,255));
al_flip_display();
al_clear_to_color(al_map_rgb(0,0,0));
}
Also I noticed that al_wait_for_event is not waiting for a new event in case of holding down a key but is in fact making the event of type ALLEGRO_EVENT_KEY_CHAR . Although this should not pose any problem , I wanted to know a bit more about it.
Also, the above code is taken from a tutorial. It worked fine over there.
To make sure your app doesn't apply the key press more than once per Key_Down event define a Boolean initialized to false. Place everything in your Key_Down events in an If statement triggering only if Boolean == false and in its block immediately set Boolean = true followed by the things you want the event to do only once per event.
Then, in the corresponding Key_Up event set
Boolean = false and you should be golden.
I haven't tested this, but it should work, and it serves towards compating your app to any client computer, no matter if they have funky key press settings on their device.

Getting the width of Win32 TreeView control

The Win32 TreeView control does not have a built-in message/macro to get its (scrollable) width, e.g. if want to set the TreeView's width so it won't need to have a scrollbar.
How can this be done?
Here's a C function to do this:
int TreeView_GetWidth(HWND hTreeWnd)
{
SCROLLINFO scrollInfo;
SCROLLBARINFO scrollBarInfo;
scrollInfo.cbSize = sizeof(scrollInfo);
scrollInfo.fMask = SIF_RANGE;
scrollBarInfo.cbSize = sizeof(scrollBarInfo);
// To find the whole (scrollable) width of the tree control,
// we determine the range of the scrollbar.
// Unfortunately when a scrollbar isn't needed (and is invisible),
// its range isn't zero (but rather 0 to 100),
// so we need to specifically ignore it then.
if (GetScrollInfo(hTreeWnd, SB_HORZ, &scrollInfo) &&
GetScrollBarInfo(hTreeWnd, OBJID_HSCROLL, &scrollBarInfo))
{
// Only if the scrollbar is displayed
if ((scrollBarInfo.rgstate[0] & STATE_SYSTEM_INVISIBLE) == 0)
{
int scrollBarWidth = GetSystemMetrics(SM_CXVSCROLL);
// This is a hardcoded value to accomodate some extra pixels.
// If you can find a cleaner way to account for them (e.g. through
// some extra calls to GetSystemMetrics), please do so.
// (Maybe less than 10 is also enough.)
const int extra = 10;
return (scrollInfo.nMax - scrollInfo.nMin) + scrollBarWidth + extra;
}
}
return 0;
}

how to set "smart" breakpoint in Xcode when method returns a specific value?

I have a method which returns a bool value, with several exit points.
However, it does not seem to work correctly, so I would like to set an automatic breakpoint to see when it returns a YES value, so I can check all the variables and calculations in the debugger.
I would like to stop the debugger whenever a YES value is returned.
I have a similar smart breakpoint set for objc_exception_throw, so I know it's possible, I am just not sure how.
(In case it helps anyone, the way you can set the exception breakpoint: in the Breakpoints window (Run -> Show -> Breakpoints) enter objc_exception_throw as "Breakpoint", and libobjc.A.dylib as "Location")
EDIT: the specific code I would like to use it for:
- (BOOL)collisionOccured {
// Assumption: helicopter is of square shape (collision calculated by radius), walls are rectangles
// This approach is based on the solution seen here: http://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection/402010#402010
float helicopterImageWidth = [helicopter texture].contentSize.width;
float wallImageWidth = [[walls lastObject] texture].contentSize.width;
float wallImageHeight = [[walls lastObject] texture].contentSize.height;
float helicopterCollisionRadius = helicopterImageWidth * 0.4f;
CGPoint helicopterPosition = helicopter.position;
int numWalls = [walls count];
for (int i = 0; i < numWalls; i++) {
CCSprite *wall = [walls objectAtIndex:i];
if ([wall numberOfRunningActions] == 0) {
// The wall is not moving, we can skip checking it.
continue;
}
CGPoint wallPosition = wall.position;
float helicopterDistanceX = abs(helicopterPosition.x - wallPosition.x - wallImageWidth/2);
float helicopterDistanceY = abs(helicopterPosition.y - wallPosition.y - wallImageHeight/2);
if (helicopterDistanceX > (wallImageWidth/2 + helicopterCollisionRadius)) { return NO; }
if (helicopterDistanceY > (wallImageHeight/2 + helicopterCollisionRadius)) { return NO; }
if (helicopterDistanceX <= (wallImageWidth/2)) { return YES; }
if (helicopterDistanceY <= (wallImageHeight/2)) { return YES; }
float cornerDistance_sq = powf((helicopterDistanceX - wallImageWidth/2), 2) +
powf((helicopterDistanceY - wallImageHeight/2), 2);
return (cornerDistance_sq <= powf(helicopterCollisionRadius, 2));
}
// this should not occur
return NO;
}
This method is called via
- (void)update:(ccTime)delta {
if ([self collisionOccured]) {
NSLog(#"A collision occured");
}
}
The problem is that the update method takes delta (time passed) as argument, so I can't check what's happening frame by frame -- whenever I continue the execution, I am presented with a different scene.
(I am using cocos2d in the code)
You can set conditional breakpoints. With a slight tweak to update:
- (void)update:(ccTime)delta {
BOOL collided = [self collisionOccured];
if (collided) {
NSLog(#"A collision occured");
}
}
you can set a breakpoint as normal after the BOOL's assignment (i.e. on the if line), then right-click on the blue breakpoint arrow and select "Show Message Bubble", and add collided as the Condition. The extra variable should get optimized away in Release build mode.
If you're using a local return variable:
- (BOOL)someMethod {
BOOL ret = NO;
if (something) {
ret = YES;
} else if (something_else) {
ret = YES;
}
// ... and so on
return ret;
}
You can just set a watch point on ret
Otherwise, you're probably stuck with stepping through the code—hopefully some clever combination of conditional breakpoints will help you not have to break on every invocation. Setting a method breakpoint like you do with objc_exception_throw wouldn't work, because it will stop on every invocation, and breaking on the return value at the calling site is too late to figure out how you got there.
If you can post the code, we may be able to give more specific help as to a debugging strategy. Good luck. :-)

Resources