Fastest way to get name of frontmost app?

I’m using some code from MBS that is run 3 times a second by a timer from a menubar app.
Activity Monitor tells me my app is using 96% CPU. It doesn’t seem to slow anything down, but it shouldn’t be this high.

The list returned by NSRunningApplicationMBS.runningApplications includes tons of background processes.

I have 7 apps open, but the list it returns has 108 items, and it has to check each one to see if that is the active (frontmost) one.

is there a better, less intensive way to get the name of the active or frontmost app?

Var n(-1) As NSRunningApplicationMBS = NSRunningApplicationMBS.runningApplications
Var t As String

For Each r As NSRunningApplicationMBS In n
  If r.Active Then
    t = r.localizedName
    Exit
  End If
Next

That sounds odd - please click the “Sample” button in Activity Monitor and post the results here, so we can see what is using all the CPU - it could be something unexpected.

image

Since you have MBS, you could do this:

Public Function GetFrontProcessInfo() as String
  dim p as new ProcessMBS
  p.GetFrontProcess
  return p.name
End Function

Edit to add: Another advantage of this method is it works on mac and windows.

1 Like

Why not NSRunningApplicationMBS.frontmostApplication.localizedName?

2 Likes

@Mark_Sweeney I just ran a test with your code, and the app is using about 1% CPU. Are you sure your timer is running 3 times per second? (333 millisecond period)

Holy cow is that how easy it is to make one of those automatic time tracking apps?

Hmm… if I ever have free time.

2 Likes

That works, thanks!

I found why CPU usage going so high… programmer error.

For some reason, in the open even I had:

While True
  App.DoEvents
Wend

As soon as I commented that out, CPU usage dropped to 2.9%

1 Like

Because I didn’t know about it?

It turns out the MBS code I was using was not the culprit. I thought getting the list and comparing it multiple times a second might have been spiking something.

It turns out I still need a part of that code to see if another menubar app is running.

A few more tweaks, and it’s now at 1.8% CPU, so I no longer get the battery usage warning on my MacBook Air :metal:t4:

1 Like

FWIW I have written a Tracking App, but unfortunately this MBS function doesn’t inform you what documents are open within the running apps, plus it is macOS only. For this reason I use a Shell command.

I would suggest to use module CGWindowMBS to get a window list of the process you watch to see what Windows are open.

1 Like