views:

164

answers:

3

Hello,

I am coding an application in C# that needs to know the current program and files a user has in focus.

I.e. I want to write functions like:

string GetProgramNameCurrentlyInFocus() { ... }
string GetFilenameCurrentlyInFocus() { ... }

Which return the current program executable filename (e.g. "word.exe") or the actual official program name (e.g. "Microsoft Word 2007"), and the current file that is being viewed by the user with the current program (e.g. "C:\Users\Mat\Documents\essay.doc"), respectively.

Products like RescueTime as well as SysInternals can do these things so it is possible. I can get the title of the current program in focus, but that is not good enough as some programs do not say the program name in the title.

So, does anyone know how to code functions like that? Any tips or places I should look?

Note: I've checked out SysInternal, and despite still being free, the source code is no longer available since Microsoft bought them out.

~Mat

+1  A: 

You can use GetForgoundWindow to get the current window in focus. I don't know a way to get what file is open.

rerun
+1  A: 

It is possible to enumerate all open handles. This would give the name of the file (or rather all open files since a process may have more than one).

Mark Wilkins
A: 

You want GetForegroundWindow then from there you can get the main module for the application (which will generally be the application that launched it).

You might be able to determine what resources its using to find open docs, but that will be a highly manual process.

GrayWizardx
Not only manual but error prone and different for every program.
rerun
@Rerun, agreed. :) But sometimes we have **managers** who insist we do stuff like that. It might not be bad if all the @Mat is doing is trying to watch a few specific apps, **all** apps is a whole different story.
GrayWizardx
Yeah, I'm supposed to be watching only a few select programs to begin with, but was inspired by the output from RescueTime, that a more general approach seemed possible.Thanks for those comments though- great help from all!Will have to report my code later on, as priorities have shifted, so maybe in a week or 2...or 3.
Mat Holroyd