I recently started coding in c #(in may this year) and well I find it best to learn by working with code. this application http://www.c-sharpcorner.com/UploadFile/satisharveti/ActiveApplicationWatcher01252007024921AM/ActiveApplicationWatcher.aspx.
I am trying to recreate it however mine will be saving the information into an sql database(new at this as well). I am having some coding problems though as it does not do what I expect it to do. THis is the main code I am using.
private void GetTotalTimer()
{
DateTime now = DateTime.Now;
IntPtr hwnd = APIFunc.getforegroundWindow();
Int32 pid = APIFunc.GetWindowProcessID(hwnd);
Process p = Process.GetProcessById(pid);
appName = p.ProcessName;
const int nChars = 256;
int handle = 0;
StringBuilder Buff = new StringBuilder(nChars);
handle = GetForegroundWindow();
appltitle = APIFunc.ActiveApplTitle().Trim().Replace("\0", "");
//if (GetWindowText(handle, Buff, nChars) > 0)
//{
// string strbuff = Buff.ToString();
// StrWindow = strbuff;
#region insert statement
try
{
if (Conn.State == ConnectionState.Closed)
{
Conn.Open();
}
if (Conn.State == ConnectionState.Open)
{
SqlCommand com = new SqlCommand("Select top 1 [Window Title] From TimerLogs ORDER BY [Time of Event] DESC", Conn);
SqlDataReader reader = com.ExecuteReader();
startTime = DateTime.Now;
string time = now.ToString();
if (!reader.HasRows)
{
reader.Close();
cmd = new SqlCommand("insert into [TimerLogs] values(@time,@appName,@appltitle,@Elapsed_Time,@userName)", Conn);
cmd.Parameters.AddWithValue("@time", time);
cmd.Parameters.AddWithValue("@appName", appName);
cmd.Parameters.AddWithValue("@appltitle", appltitle);
cmd.Parameters.AddWithValue("@Elapsed_Time", blank.ToString());
cmd.Parameters.AddWithValue("@userName", userName);
cmd.ExecuteNonQuery();
Conn.Close();
}
else if(reader.HasRows)
{
reader.Read();
if (appltitle != reader.ToString())
{
reader.Close();
endTime = DateTime.Now;
appduration = endTime.Subtract(startTime);
cmd = new SqlCommand("insert into [TimerLogs] values (@time,@appName,@appltitle,@Elapsed_Time,@userName)", Conn);
cmd.Parameters.AddWithValue("@time", time);
cmd.Parameters.AddWithValue("@appName", appName);
cmd.Parameters.AddWithValue("@appltitle", appltitle);
cmd.Parameters.AddWithValue("@Elapsed_Time", appduration.ToString());
cmd.Parameters.AddWithValue("@userName", userName);
cmd.ExecuteNonQuery();
reader.Close();
Conn.Close();
}
}
}
}
catch (Exception)
{
}
//}
#endregion
ActivityTimer.Start();
Processing = "Working";
}
Unfortunately this is the result.
it is not saving the data as I expect it to. What am i doing wrong I had thought that with the sql reader it would first check for a value and only save if they do not match however it is saving whether there is a match or not.