6
我想在計時器停止時獲取當前活動應用程序的名稱。記錄20秒後,它應顯示當前活動的應用程序名稱。我嘗試了一些代碼。你可以在這裏看到。但在計時器停止後它沒有顯示任何東西。獲取當前活動的應用程序名稱
C#代碼:
public class Win32wrapper
{
private System.Timers.Timer pingTimer;
private Timer recordTimer;
private List<HarvestApp.ProcessInformation> ProcessList = new List<HarvestApp.ProcessInformation>();
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
private DateTime recordStartTime;
public void startTimer(int pingTimerValue=5000, int recordTimerValue=20000)
{
pingTimer = new System.Timers.Timer(pingTimerValue);
pingTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
pingTimer.Interval = pingTimerValue;
pingTimer.Enabled = true;
recordTimer = new Timer(recordTimerValue);
recordTimer.Elapsed += new ElapsedEventHandler(OnRecordEvent);
recordTimer.Interval = recordTimerValue;
recordTimer.Enabled = true;
recordStartTime = DateTime.Now;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Ping Elapsed event was raised at {0}", e.SignalTime);
//Record through win32dll the application foreground caption
GetActiveFileNameTitle();
//Store into collection object, Push into ArrayList, Push into process id
}
public String GetActiveFileNameTitle()
{
IntPtr hWnd = GetForegroundWindow();
uint processId;
GetWindowThreadProcessId(hWnd, out processId);
Process p = Process.GetProcessById((int)processId);
//p.MainModule.FileName.Dump();
return p.ProcessName;
}
private void OnRecordEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Record Elapsed event was raised at {0}", e.SignalTime);
ProcessInformation procTemp = GetMaxRunTimeForApplicationsBetween(recordStartTime, DateTime.Now);
Harvest_TimeSheetEntry tempEntry = new Harvest_TimeSheetEntry(procTemp, recordStartTime, DateTime.Now);
//Add to the list of the specific day Only not the entire
// Globals._globalController.harvestManager._TIMESHEETENTRYDICTIONARY[recordStartTime.Date].Add(tempEntry);
Globals._globalController.getDayViewWindow.Dispatcher.BeginInvoke(new Action(delegate()
{
Globals._globalController.getDayViewWindow.addHarvestEntrytoView(tempEntry);
}));
//Clean Out the ProcessList?
recordStartTime = DateTime.Now;
}
public void stopTimer()
{
pingTimer.Stop();
recordTimer.Stop();
}
你想知道當前窗口的標題? http://stackoverflow.com/questions/115868/how-do-i-get-the-title-of-the-current-active-window-using-c – Lucas
我想要的應用程序的名稱。如果記事本在後臺運行,那麼它應該在那裏顯示我的名字爲「記事本」。 – Dinesh
問題是:你想要窗口標題還是前臺應用程序的進程名稱? – Andre