【发布时间】:2014-01-14 15:42:34
【问题描述】:
嘿,我在 C# 中找到了这段代码here,它允许使用 SendMessage API 从正在运行的 2 个 .net 应用程序来回发送消息。测试时 C# 代码一切正常,但我需要将其转换为 VB.net。
所以我使用了一个在线 C#->VB.net 转换器并得到了这个:
导入 System.Runtime.InteropServices
Public Class Form1
Inherits System.Windows.Forms.Form
Private Const RF_TESTMESSAGE As Integer = &HA123
<DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
Public Shared Function SendMessage(ByVal hwnd As IntPtr, <MarshalAs(UnmanagedType.U4)> ByVal Msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
End Function
Public Sub New()
InitializeComponent()
Me.Text = String.Format("This process ID: {0}", Process.GetCurrentProcess().Id)
End Sub
<STAThread()> Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim proc As Process = Process.GetCurrentProcess()
Dim processes As Process() = Process.GetProcessesByName(proc.ProcessName)
If processes.Length > 1 Then
For Each p As Process In processes
If p.Id <> proc.Id Then
SendMessage(p.MainWindowHandle, RF_TESTMESSAGE, IntPtr.Zero, IntPtr.Zero)
End If
Next
Else
MessageBox.Show("No other running applications found.")
End If
End Sub
Protected Overrides Sub WndProc(ByRef message As Message)
If message.Msg = RF_TESTMESSAGE Then
ListBox1.Items.Add("Received message RF_TESTMESSAGE")
End If
MyBase.WndProc(message)
End Sub
End Class
但是,当它到达 If processes.Length > 1 Then 时,对我的两个应用程序使用上面的代码似乎不会产生任何发送消息操作。它总是告诉我没有找到其他正在运行的应用程序。即使我有两个应用程序都在运行,就像我在 C# 示例中所做的那样。
我一定遗漏了一些在转换时没有遗留下来的东西。任何帮助都会很好地解决这个问题!
【问题讨论】:
-
both apps running- 同一程序的两个实例,还是不同的程序?顺便说一句,你为什么不使用 WCF? -
天哪,学习如何编写 C# 代码将比让转换后的废话运行所需的时间更少。这是我的建议,现在理解 C# 对 VB.NET 程序员来说是一项相当艰巨的要求。
-
您提供的博文链接在这里不起作用。也许是时候考虑使用一流的进程间通信方法,如 WCF,甚至是 Remoting。另见stackoverflow.com/questions/2082450/…
-
@AlexFarber 它的不同程序。每个都在自己的 IDE VS2010 中运行。在链接的示例中,我有相同的设置,他们都互相交谈得很好。
-
@RobertHarvey 该帖子确实有效...也许在您尝试访问它时遇到了问题?我的代码已经是 Win 形式,所以现在不能选择 WCF。
标签: c# vb.net api sendmessage