Wednesday, November 2, 2011

Transparent NSWindow controls

If you are trying to find a way to make a NSWindow transparent then you should have a look at one of my earlier posts, titled "Draggable transparent NSWindow". Today I'm going to show you how to have the default NSWindow title bar controls (close,minimize,maximize).

Step 01:
Design images for the buttons. You require two sets of images, one set for when it is focused and another for when it is not (default).

Step 02:
Add NSButtons using the IB (Interface Builder) and set the images (default).

Step 03:
Tell the NSWindow to accept mouse moved events by placing the following code inside the "init" method in your NSWindow subclass.

[self setAcceptsMouseMovedEvents:TRUE];

Step 04:
Track mouse movements and change the button images when the user moves the mouse on top of them. Have the following in your NSWindow subclass.

- (void)mouseMoved:(NSEvent *)theEvent{
[super mouseMoved:theEvent];
theEvent = nil;
NSPoint point = [self mouseLocationOutsideOfEventStream];
//btnClose is the IBOutlet I have for the close button
int minX = btnClose.frame.origin.x;
int minY = btnClose.frame.origin.y;
int x = point.x;
int y = point.y;
int maxX = btnClose.frame.origin.x + 15;
int maxY = btnClose.frame.origin.y + 15;
BOOL mouseOnTop = FALSE;

if ((minX <= x) && (x <= maxX)) {
if ((minY <= y) && (y <= maxY)){
mouseOnTop = TRUE;
}
}else{
mouseOnTop = FALSE;
}
if (mouseOnTop) {
if (![[btnClose image] isEqual:btnRedImage]) {
[btnClose setImage:btnRedImage];
}
// NSLog(@"mouse on top");
}else{
if (![[btnClose image] isEqual:btnBlackImage]) {
[btnClose setImage:btnBlackImage];
}
// NSLog(@"mouse not on top");
}
// NSLog(@"mouseMoved x:%d, y:%d",x,y);
// NSLog(@"btnClose origin x:%d, y:%d",minX,minY);
// NSLog(@"btnClose max x:%d, y:%d",maxX,maxY);
}

Step 05: Bind the button events

1 comment:

NSWindow said...

This method will only work when the app is on focus. I noticed that the default NSWindow controls get highlighted if we move the mouse over them even when the window is not on focus.