using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using System.IO; namespace TopMostWinChecker { public partial class Form1 : Form { Timer m_timer; int m_iHandle=0; public Form1() { InitializeComponent(); m_timer = new Timer(); m_timer.Interval = 100; m_timer.Tick += new EventHandler(TimerHandler); m_timer.Start(); } private void TimerHandler(object sender, EventArgs e) { int iHandle = GetForegroundWindow(); const int nChars = 256; StringBuilder Buff = new StringBuilder(nChars); if(GetWindowText(iHandle, Buff, nChars) > 0) { if(iHandle != m_iHandle) { string strCurTime = System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); ListViewItem item = new ListViewItem(new string[]{ Buff.ToString(), iHandle.ToString(), strCurTime }); lvList.Items.Add(item); StreamWriter fp = null; try { fp = new StreamWriter("save.txt", true); fp.WriteLine("[" + strCurTime + "] " + Buff.ToString() + " (" + iHandle.ToString() + ")"); } catch { MessageBox.Show("file save failed"); } finally { if(fp != null) fp.Close(); } } } m_iHandle = iHandle; } [DllImport("user32.dll")] static extern int GetForegroundWindow(); [DllImport("user32.dll")] static extern int GetWindowText(int hWnd, StringBuilder text, int count); } }