Golang获取MacOS Cocoa窗口事件的方法
Golang获取MacOS Cocoa窗口事件的方法 你好,我是Go语言的新手,正在尝试为macOS编写一个处理特定文件类型(扩展名)的工具。Info.plist文件配置正确且已成功关联,但macOS不会将文件名作为命令行参数提供。相反,它会发送一些窗口通知(?)。我能够获取到一个窗口句柄(Sciter窗口),但之后就卡住了。
关于如何获取这些通知以便得到文件名,有什么想法吗?
1 回复
更多关于Golang获取MacOS Cocoa窗口事件的方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在macOS上处理文件关联事件时,可以通过Cocoa的NSApplicationDelegate协议来获取文件打开事件。以下是使用Go通过C绑定实现的方法:
// #cgo CFLAGS: -x objective-c
// #cgo LDFLAGS: -framework Cocoa
// #import <Cocoa/Cocoa.h>
//
// extern void handleOpenFile(const char* filename);
//
// @interface AppDelegate : NSObject <NSApplicationDelegate>
// @end
//
// @implementation AppDelegate
// - (void)application:(NSApplication *)app openFiles:(NSArray<NSString *> *)filenames {
// for (NSString* filename in filenames) {
// handleOpenFile([filename UTF8String]);
// }
// }
//
// - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender {
// return YES;
// }
// @end
//
// void setupAppDelegate() {
// AppDelegate* delegate = [[AppDelegate alloc] init];
// [[NSApplication sharedApplication] setDelegate:delegate];
// }
import "C"
import (
"fmt"
"unsafe"
)
//export handleOpenFile
func handleOpenFile(filename *C.char) {
goFile := C.GoString(filename)
fmt.Printf("文件已打开: %s\n", goFile)
// 在这里处理文件路径
}
func main() {
C.setupAppDelegate()
// 启动Cocoa事件循环
app := C.NSApp
C.NSApplicationMain(C.int(0), nil)
}
如果需要处理Sciter窗口事件,可以结合Sciter的API:
// #cgo CFLAGS: -I/path/to/sciter-sdk/include
// #cgo LDFLAGS: -L/path/to/sciter-sdk/bin.osx -lsciter
// #include <sciter-x.h>
// #include <sciter-x-window.h>
import "C"
func setupSciterWindow() {
// 创建Sciter窗口
var hwnd C.HWINDOW
C.SciterCreateWindow(C.SW_MAIN, nil, nil, nil, &hwnd)
// 设置窗口事件处理
C.SciterSetCallback(hwnd, C.SCITER_CALLBACK(C.sciterCallback), nil)
}
//export sciterCallback
func sciterCallback(pns C.LPSCITER_CALLBACK_NOTIFICATION, callbackParam unsafe.Pointer) C.UINT {
// 处理Sciter通知
return C.SC_LOAD_DATA
}
确保在Info.plist中正确配置CFBundleDocumentTypes:
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>your_ext</string>
</array>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>
</array>
编译时需要指定Objective-C运行时:
go build -o app main.go

