如果文件是由用户打开的,则将行粘贴到文件的记事本
本文关键字:文件 记事本 用户 如果 | 更新日期: 2023-09-27 18:29:57
我正在为我的程序创建一个日志记录机制,在该机制中,我必须将数据记录到一个文件中,该文件的位置和名称由用户指定。
我正在使用流写入程序进行日志记录,如下所示-
StreamWriter writer = Writer ?? File.AppendText(FileName);
writer.WriteLine(DateTime.Now + " " + text);
writer.Flush();
writer.Close();
但是,如果用户在我的程序运行时打开文件,那么在用户关闭并重新打开文件之前,新记录的行对用户来说是不可见的。我可以通过他们的任何方式克服这种行为吗?当文件打开时,用户也可以看到新记录的线。
使用FindWindow和sendmessage找到了一个解决方案以下是相同的-的代码
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string lp1, string lp2);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
extern static IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, [In] string lpClassName, [In] string lpWindowName);
[DllImport("User32.dll", EntryPoint = "SendMessage")]
extern static int SendMessageGetTextLength(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, int lParam);
// Writes text line into log file.
// If the log file is opened with notepad, it is pasted there instead
static public void Log(string inputText, DateTime startTime = new DateTime())
{
try
{
/* DateTime now = DateTime.Now;
inputText = now.ToString() + " " + inputText;
if (startTime != new DateTime())
{
double diffTime = (int)(now - startTime).TotalMilliseconds;
String t;
if (diffTime >= 10000)
t = ((int) diffTime / 10000).ToString() + " s";
else
t = ((int)diffTime).ToString() + " ms";
inputText += ", " + t;
}
*/ //irrelevant to the answer
// search for log file opened with notepad
IntPtr editBox = GetNotepadWindow();
if (editBox == IntPtr.Zero)
{
// log file is not open => append line to file
try
{
var writer = new StreamWriter(LogFile, true);
writer.WriteLine(inputText);
writer.Flush();
writer.Close();
}
catch
{
}
return;
}
// paste line into notepad
int length = SendMessageGetTextLength(editBox, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
SendMessage(editBox, EM_SETSEL, length, length); // search end of file position
inputText += "'r'n";
SendMessage(editBox, EM_REPLACESEL, 1, inputText); // append new line
}
catch
{
}
}
static private IntPtr GetNotepadWindow()
{
string windowName = LogFile;
if (string.IsNullOrEmpty(LogFile))
windowName = "Untitled";
int index = windowName.LastIndexOf('''');
if (index >= 0)
windowName = windowName.Substring(index+1);
IntPtr mainWindow = FindWindow("Notepad", windowName + " - Notepad");
IntPtr editBox = IntPtr.Zero;
if (mainWindow != IntPtr.Zero)
editBox = FindWindowEx(mainWindow, new IntPtr(0), "Edit", null);
return editBox;
}