【问题标题】:Excel VBA to Windows Form Application Process CommunicationExcel VBA 到 Windows 窗体应用程序进程通信
【发布时间】:2019-01-02 20:35:31
【问题描述】:

我的任务是处理一个应用程序,其中 Excel 电子表格需要直接从客户端上并排运行的 Windows 窗体应用程序中检索/访问值。我一直在阅读将 .NET 组件暴露给 COM 的内容,并且我已经能够从 excel 中编译、注册和使用它们。但是,到目前为止,我所阅读的任何内容都不允许我直接进入正在运行的 Windows 进程/窗体并访问窗体本身的一些值,因为我总是必须在 VBA 中“新建”.NET 对象并且无法访问当前线程。我的问题是:

  • 是否可以有直接进程来处理 Excel 电子表格和 Windows 窗体应用程序之间的通信(无中间数据库或文件)?
  • 是否可以将 .NET Windows 窗体应用程序的输出编译成 .dll?到目前为止,我只能让它生成一个.exe。

如果措辞不当,请告诉我,我可以尝试更好地解释问题。

感谢您的帮助。

【问题讨论】:

标签: excel vba winforms-interop


【解决方案1】:

我认为最好的方法是在窗口之间使用消息。 这是一个从 vb6 发送到 vb.net 的示例,您可以将其调整为 vba:

vb6 代码:

Private Sub cmdSendData_Click()
Dim sString As String
Dim lHwnd As Long
Dim cds As COPYDATASTRUCT
Dim buf(1 To 255) As Byte

sString = Trim$(txtString)
If sString = "" Then Exit Sub
'
' Get the handle of the target application's visible window.
'
lHwnd = FindWindow(vbNullString, cWINDOW_TITLE)
'
' Copy the string into a byte array,
' converting it to ASCII. Assign lpData
' the address of the byte array.
'
Call CopyMemory(buf(1), ByVal sString, Len(sString))
With cds
    .dwData = 3
    .cbData = Len(sString) + 1
    .lpData = VarPtr(buf(1))
End With
'
' Send the string.
'
Call SendMessage(lHwnd, WM_COPYDATA, Me.hwnd, cds)
End Sub

vb.net 代码:

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    If m.Msg = MainForm.WM_COPYDATA Then
      Dim data As CopyData
      Dim message As String

      ' get the data...
      data = CType(m.GetLParam(GetType(CopyData)), CopyData)
      Dim B(255) As Byte
Marshal.Copy(data.lpData, B, 0, 255)
message = System.Text.Encoding.Default.GetString(B
      ' add the message
      Messages.Items.Add(String.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), message))

      ' let them know we processed the message...
      m.Result = New IntPtr(1)
    Else
      MyBase.WndProc(m)
    End If
  End Sub

  Private Const WM_COPYDATA As Integer = &H4A

  <StructLayout(LayoutKind.Sequential)> _
  Private Structure CopyData
    Public dwData As IntPtr
    Public cbData As Integer
    Public lpData As IntPtr
  End Structure

【讨论】:

  • 谢谢豪尔赫。我会试试看。
猜你喜欢
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多