嘿,我在C#中发现了这个代码here,它允许使用SendMessage API从运行的2个.net应用程序来回发送消息。测试时C#代码的一切顺利,但我需要将其转换为VB.net。
所以我使用了在线C# - > VB.net转换器并得到了这个:
Imports 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&gt;时,似乎不会产生任何sendmessage操作。 1然后。它总是告诉我没有找到其他正在运行的应用程序。即使我在C#示例中运行了这两个应用程序。
我必须遗漏一些在转换时没有遗留下来的东西。任何帮助都可以很好地解决这个问题!
答案 0 :(得分:0)
您收到“未找到其他正在运行的应用程序”消息表明此代码中存在问题。看看我的笔记:
Dim proc As Process = Process.GetCurrentProcess()
//This gets an array of all processes currently running with the same name
// as this application.
Dim processes As Process() = Process.GetProcessesByName(proc.ProcessName)
//If there is only one process with this application's name, then it's
// THIS process, so there aren't any others by the same name running
// right now.
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
//Thus, this gets called because there are not other applications with
//the same name.
MessageBox.Show("No other running applications found.")
End If
请注意,当您在环境中运行代码时,现代工作室版本通常会显示为DevEnv.exe,因此运行IDE 的两个实例通常可以正常工作。然而! Visual Studio中有一个选项可以在其自己的应用程序(可执行文件)名称下运行代码。如果你转到Project Properties
- &gt; Debug
,标有Enable the Visual Studio hosting process
的选项。禁用该复选框将导致代码在其已编译的可执行文件的名称下运行。