Qt provides platform-related event filtering functions for different platforms, such
| Bool QApplication: x11EventFilter (XEvent * event) [virtual] |
Generally, a developer can derive a QApplication and then rewrite the function to obtain all X11 events of the program. Similar functions can be rewritten on other platforms. However, when I was working on Mac-related programs, I found such a paragraph in the document.
|
"Bool QApplication: macEventFilter (EventHandlerCallRef caller, EventRef event) [virtual]
Warning: This virtual function is only implemented under Mac OS X when against Carbon ." |
This indicates that when Cocoa is used, the standard Qt method cannot intercept program events. The document also describes how to do this in Cocoa to get the event:
| "Cocoa uses a different event system which means this function is not called when building Qt against Cocoa. if you want similar functionality subclass NSApplication and reimplement the sendEvent: message to handle all the NSEvents. you also will need to instantiate your custom NSApplication before creating a QApplication. seeApple's NSApplication Reference for more information." |
This article is very detailed and specific, but since I know little about Mac programming, I still feel a little confused at the moment. I believe many of my friends have the same concerns as the author. By searching for examples and documents on the Internet, I have finally completed a small example. I would like to share it with many qters and hope to help you. Let's talk less about the Code:
- #include
-
- #include
-
- #include "mainwin.h"
-
- @interface KeyLoggerApplication : NSApplication
-
- {
-
- }
-
- @end
-
- @implementation KeyLoggerApplication
-
- - (BOOL)sendEvent:(NSEvent *)anEvent {
-
- NSEventType type = [anEvent type];
-
- bool handled = NO;
-
- if (type == NSKeyUp)
-
- {
-
- switch( [anEvent keyCode] )
-
- {
-
- default:
-
- NSLog(@"Keypressed: %d, **%@**", [anEvent keyCode], [anEvent characters]);
-
- break;
-
- }
-
- }
-
- //handle only the keys i need then let the other go through the regular channels
-
- //this stops the annoying beep
-
- if( !handled )
-
- [super sendEvent:anEvent];
-
- }
-
- @end
-
- int main(int argc, char* argv[])
-
- {
-
- [KeyLoggerApplication sharedApplication];
-
- QApplication a(argc, argv);
-
- MainWin mw;
-
- mw.show();
-
- return a.exec();
-
- }
The above code prints the keyboard-pressed event to the console. In addition to the syntax of Objective C, there is no difficulty. I believe everyone can understand it. Another note is that the file stored in this code must be. mm is the suffix, that is, the main. cpp should be changed to main. mm, the corresponding pro file also needs to be modified. "LIBS + =-framework AppKit" must be added to the pro, because NSApplication and other APIs provided by AppKit are used.
I personally think these strange Mac programming rules are a little too different, and I don't like them very much.