Hi - my code below runs ok as a windows form - but when I change to a service, it does not appear to be able to read the window name which has focus.
Is a windows service able to read the GetForegroundWindow() function?
Thanks, Mark
Imports System Imports System.Configuration Imports System.Collections.Generic Imports System.ComponentModel Imports System.Data Imports System.Text Imports System.Runtime.InteropServices Imports System.Security Imports System.Security.Principal.WindowsIdentity Imports dtmonitor Public Class Service1 <DllImport("user32.dll")> _ Private Shared Function GetForegroundWindow() As Integer End Function <DllImport("user32.dll")> _ Private Shared Function GetWindowText(ByVal hWnd As Integer, ByVal text As StringBuilder, ByVal count As Integer) As Integer End Function Protected Overrides Sub OnStart(ByVal args() As String) Timer1.Enabled = True End Sub Protected Overrides Sub OnStop() ' Add code here to perform any tear-down necessary to stop your service. End Sub Private Sub Timer1_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Timer1.Elapsed Const nChars As Integer = 256 Dim handle As Integer = 0 Dim Buff As New StringBuilder(nChars) handle = GetForegroundWindow() Dim winnamelocal As String = "" If GetWindowText(handle, Buff, nChars) > 0 Then winnamelocal = Buff.ToString() End If Dim un As String = GetCurrent.Name Dim i As Integer = GetCurrent.Name.IndexOf("\") If i > 0 Then un = un.Substring(i + 1, un.Length - i - 1) End If Dim tme As DateTime = DateTime.Now Dim secs As Integer = DateDiff(DateInterval.Second, dtmonitor.My.MySettings.Default.curtime, tme) Dim tsDiff As New TimeSpan Dim fs As New System.IO.FileStream("c:\mtWindowsService.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write) Dim m_streamWriter As New System.IO.StreamWriter(fs) m_streamWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End) m_streamWriter.WriteLine("name: " & un) m_streamWriter.WriteLine("window: " & winnamelocal) m_streamWriter.WriteLine("tme: " & tme.ToString) m_streamWriter.Flush() m_streamWriter.Close() End Sub End Class