最近本人在搞个程序,一个小功能是需要在程序开始时判断是否有已存在的实例在运行,如果有就告诉那个实例去打开文件(传递个字符串过去)然后结束当前实例.功能就是自动在一个MDI窗口中打开多个文档.
最开始我设想用DDE实现,忽然发现VB2010已经舍弃DDE了,大悲
后来又想到用写文件和注册表的方法,一想效率太低,用socket在没网卡的机子上就是个悲剧,而且这个程序和网络没关系,用socket容易触发防火墙的提示
然后我又用Sendmessage函数+Windows消息+内存映射文件,终于成功了,问题是现在需要.Net4.0支持,很多学校电脑只有.Net3.5,我演示的时候会悲剧......现在求助各位,如何用Sendmessage传递个字符串参数?wParam和lParam都是数字类型的,没法传递字符串,我试过传递指针和结构,都悲剧....
这是我的程序:
Public Class Form1
<Runtime.InteropServices.DllImport("user32.dll", CharSet:=Runtime.InteropServices.CharSet.Unicode, entrypoint:="SendMessageW")> _
Public Shared Function SendMessage(ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As IntPtr, ByVal lParam As Integer) As Integer
End Function
Protected Overrides Sub DefWndProc(ByRef m As System.Windows.Forms.Message)
Select Case m.Msg
Case &H400
If m.WParam = 3180 Then
Dim s As New IO.StreamReader(IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen("asdn.open", 1024).CreateViewStream())
openfile(s.ReadToEnd)
End If
Case Else
MyBase.DefWndProc(m)
End Select
End Sub
Sub openfile(f)
Text = f
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
If My.Application.CommandLineArgs.Count = 1 Then
Dim Proc_List As Process() = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)
If Proc_List.Length > 1 Then
For Each i As Process In Proc_List
If XXXX <> Process.GetCurrentProcess().Id Then Dim s As New IO.StreamWriter(IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen("asdn.open", 1024).CreateViewStream())
s.Write(My.Application.CommandLineArgs(0))
s.Flush()
s.Close()
SendMessage(i.MainWindowHandle, &H400, 3180, 0)
End If
Next
Me.Close()
Else
openfile(My.Application.CommandLineArgs(0))
End If
End If
End Sub
End Class