強火で進め

このブログではプログラム関連の記事を中心に書いてます。

アクティブなアプリケーションの名前を取得

(2009/05/14 修正)
※「アクティブなウィンドウの名前を取得」というタイトルでしたが正しいタイトルでなかったので修正しました。

アクティブなアプリケーションの名前を取得するサンプルです。

アクティブなアプリケーションの名前は以下の記述で取得できます。

	NSString* appName = [[[NSWorkspace sharedWorkspace] activeApplication] valueForKey:@"NSApplicationName"];

タイマーで定期的にチェックを行っています。

- (void)checkActiveWindow:(NSTimer *)timer
{
	NSString* appName = [[[NSWorkspace sharedWorkspace] activeApplication] valueForKey:@"NSApplicationName"];
	
	[lblActiveWindow setStringValue:appName];
}

ウィンドウが常に最前面に来る様に以下の設定をしています。

	[window setLevel:CGShieldingWindowLevel()];

主な処理は以下の様になります。

- (id)init
{
    if ((self = [super init])) {
		timer = nil;
		bEnableTimer = NO;
    }
    return self;
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
	// ウィンドウを最前面に固定する
	[window setLevel:CGShieldingWindowLevel()];
}

// タイマーの停止
- (void)stopTimer
{
	// 念のためタイマーが有効か確認し、停止する
	if ([timer isValid]){
		[timer invalidate];
		timer = nil;
	}
}

- (IBAction)pushButton:(id)sender
{
	if (!bEnableTimer) {
		// タイマーが起動していないとき
		
		[btnTimer setTitle:@"stop"];
		timer = [[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkActiveWindow:) userInfo:nil repeats:YES] retain];
	}else{
		// タイマーが起動しているとき
		
		[btnTimer setTitle:@"start"];
		[self stopTimer];
	}
	bEnableTimer = !bEnableTimer;
}

- (void)checkActiveApplication:(NSTimer *)timer
{
	NSString* appName = [[[NSWorkspace sharedWorkspace] activeApplication] valueForKey:@"NSApplicationName"];
	
	[lblActiveWindow setStringValue:appName];
}

- (void)dealloc
{
	[self stopTimer];
	[super dealloc];
}

ソースコードこちら
※「start」ボタンを押すとアクティブなウィンドウのチェックを開始します。