应用程序活动记录器

时间:2014-09-08 23:26:57

标签: c#

我试图在C#中创建一个事件记录器。程序有一个文本框,在运行时应打开一个记事本文档,该文档将在文本框中显示用户的活动。到目前为止,我知道如何将文件保存到文本文件中以及打开它们。我也知道如何将textChanged事件用于2个文本框,但不能使用文本编辑应用程序(如记事本)。有人可以帮我指出正确的方向,并告诉我如何去做这件事。记住冗长的文字,希望我有意义:-)

1 个答案:

答案 0 :(得分:0)

您可以使用Sytem.Diagnostics.Process启动进程,然后使用SendKey.Send将文本发送到notpad窗口。试试这个:

将这些api调用添加到您的班级:

[DllImport("user32.dll",EntryPoint="FindWindow")]
private static extern IntPtr FindWindow(string sClass, string sWindow);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

将此添加到您的事件处理程序(textbox.TextChanged / button.Clicked):

IntPtr notepadHwnd = FindWindow("Notepad",(string)null);
if (notepadHwnd == null)
{
  System.Diagnostics.Process notepad = new Process();
  notepad.StartInfo.FileName = "notepad.exe";
  notepad.Start();
  System.Threading.Thread.Sleep(500);
  notepadHwnd = FindWindow("Notepad",(string)null);
}
// get the text from the users input
string msg = textBox1.Text;
if (notepadHwnd != null)
{    
   SetForgroundWindow(notepadHwnd);

   // Send the string to the application that has focus 
   // note: If you need to erase existing text (ie. on TextChanged) 
   // you could use SendKeys.Send("^a{BACKSPACE}"); to select all and delete
   SendKeys.Send(msg);
}

编辑:添加了FindWindow和SetForgroundWindow。此代码假定您没有打开任何其他记事本窗口