我有一个包含表单的 Excel VBA 宏。我希望 VB.net 隐藏表单或控制它并单击“X”按钮或自定义“退出”按钮。
有人有这方面的经验吗?
Sendkeys 非常不可靠。
如果您可以从 VB.Net 自动化 Excel,我建议您这样做。如果您对从 VB.Net 自动化 Excel 感兴趣,请参阅此。
如果您不想自动化但想直接处理它,那么我建议使用FindWindow
and Sendmessage
API 来控制表单。请参阅此示例。
假设 Excel 中有一个用户表单,看起来像这样
使用此代码形式 VB.Net
代码:
Imports System.Runtime.InteropServices
Imports System.Text
Public Class Form1
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindow( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) As IntPtr
End Function
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function SendMessage(ByVal hWnd As IntPtr, _
ByVal Msg As UInteger, _
ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Boolean
End Function
Private Const WM_CLOSE = &H10
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim Ret As Integer
'~~> Get the handle of the Excel Userform named "Example"
Ret = FindWindow(vbNullString, "Example")
'~~> If Found
If Ret <> 0 Then
'~~> Close the Window
SendMessage(Ret, WM_CLOSE, CLng(0), CLng(0))
End If
End Sub
End Class