一 讀寫txt方式
多個程式同時讀寫一個txt時,按如下的方式,可避免txt被同時操作的問題。FileStream fStream = new FileStream(strPath,XXX,FileAccess.ReadWrite,FileShare.ReadWrite)
FileShare Enumeration
Member nameDescription Delete
Allows subsequent deleting of a file.
Inheritable
Makes the file handle inheritable by child processes. This is not directly supported by Win32.
None
Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.
Read
Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
ReadWrite
Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed.However, even if this flag is specified, additional permissions might still be needed to access the file.(什麼叫做additionnal permissions?下面的代碼中為FileShare.ReadWrite,若FileStream的執行個體沒有close,其它程序不能通路txt檔案)
Write
Allows subsequent opening of the file for writing. If this flag is not specified, any request to open the file for writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
//write
string txtFullPath = "F:\\Signal\\signal.txt";
FileStream fs = new FileStream(txtFullPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sr = new StreamWriter(fs);
sw.WriteLine("Signal is out!");
sw.Close();
fs.Close();
//read
string txtPath1 = "F:\\Result\\result.txt";
FileStream stream = new FileStream(txtPath1, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamReader read = new StreamReader(stream);
string strRead = read.ReadToEnd();
stream.Seek(0, SeekOrigin.Begin);
stream.SetLength(0);// 将txt置空
stream.Close();
read.Close();
二 SendMessage方式
Demo 下載下傳連結: http://download.csdn.net/download/qq_20161893/10029669
Demo中實作了兩個窗體程式間互發消息
上面的Demo中是通過視窗标題欄的名稱擷取,通過這種方法,兩個程式中的視窗句柄都可以正确擷取。但是int processHandle = FindWindow(null, "XXX”) 對于公司的軟體卻傳回0,暫原因不明。
換個思路,先通過程式名得到PID(XXX.exe為XXX,這個地方有個坑,vs調試啟動,是XXX.vshost,而不是XXX),而後通過PID擷取程式句柄。
using System.Diagnostics;
using System.Runtime.InteropServices;
Process[] localByName = Process.GetProcessesByName("XXX");
IntPtr processHandle1 = localByName[0].MainWindowHandle;
最終效果如下:點選發送,另一個程式收到消息後彈出對話框
