0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift:左右のCommandキー同時押しを検出する方法

Posted at

はじめに

常駐型アプリを作っている際に左右のCommandキーやControlキーの同時押しでイベントを発火したくなった.
公開されているフレームワークでいいものが見つからなかったので,自作してみた.

実装例

AppDelegate.swift
import Cocoa

let LEFT_COMMAND: UInt16 = 0x37
let RIGHT_COMMAND: UInt16 = 0x36

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    private var monitors = [Any?]()
    private var flagL: Bool = false
    private var flagR: Bool = false

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        func setMonitor() {
            monitors.append(NSEvent.addLocalMonitorForEvents(matching: NSEvent.EventTypeMask.flagsChanged, handler: { (event) -> NSEvent? in
                self.judge(keyCode: event.keyCode)
                return event
            }))
            monitors.append(NSEvent.addGlobalMonitorForEvents(matching: NSEvent.EventTypeMask.flagsChanged, handler: { (event) in
                self.judge(keyCode: event.keyCode)
            }))
        }
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        for monitor in monitors {
            NSEvent.removeMonitor(monitor!)
        }
        monitors.removeAll()
    }

    func judge(keyCode: UInt16) {
        if !flagL && !flagR {
            if keyCode == LEFT_COMMAND {
                flagL = true
            } else if keyCode == RIGHT_COMMAND {
                flagR = true
            }
        } else if flagL && !flagR {
            if keyCode == LEFT_COMMAND {
                flagL = false
            } else if keyCode == RIGHT_COMMAND {
                flagR = true
            }
        } else if !flagL && flagR {
            if keyCode == LEFT_COMMAND {
                flagL = true
            } else if keyCode == RIGHT_COMMAND {
                flagR = false
            }
        } else {
            if keyCode == LEFT_COMMAND {
                flagL = false
            } else if keyCode == RIGHT_COMMAND {
                flagR = false
            }
        }
        if flagL && flagR {
            Swift.print("hello!")
        }
    }

}

どちらのCommandキーを先に押してもイベントが発火されるが,別の修飾キーも同時に押した場合でも発火してしまう(shift + left-command + right-commandなど).

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?