【问题标题】:Bringing Excel SaveAs Dialog to front Visual Basic (not VBA)将 Excel SaveAs 对话框置于 Visual Basic(不是 VBA)的前面
【发布时间】:2012-01-07 07:41:46
【问题描述】:
我编写了一个连接到 Access 数据库的 Visual Basic 程序,生成一些 SQL 语句,然后尝试将结果写入 excel 文件。
一切正常,除了调用 SaveAs 对话框时:
xlApp.Dialogs(Excel.XlBuiltInDialog.xlDialogSaveAs).Show()
对话框在程序后面,已最大化。因此,程序在等待对话框关闭时似乎挂起,但无法访问对话框(Alt+Tab 除外,但这是一个丑陋的解决方法)。
我有什么方法可以将对话框强制到前面?我找到了一个相关的线程here,但我没有处理单独的线程。那里的 OP 建议使用 BringToFront 方法,但我不确定如何将它与我的 xlApp.Dialogs 一起使用。
提前感谢您的帮助!
【问题讨论】:
标签:
visual-studio-2010
export-to-excel
savefiledialog
【解决方案1】:
找到窗口句柄并调用SetForegroundWindow
Public Function FindWindowByPartialTitle(ByVal _
TestFlex_string As String) As Long
m_TestFlexString = TestFlex_string
m_TestFlexHwnd = 0
' Enumerate windows.
EnumWindows AddressOf EnumCallback, 0
' Return the hWnd found (if any).
FindWindowByPartialTitle = m_TestFlexHwnd
End Function
' Check a returned task to see if it's the one we want.
Public Function EnumCallback(ByVal app_hWnd As Long, ByVal _
param As Long) As Long
Dim buf As String
Dim title As String
Dim Length As Long
' Get the window's title.
Length = GetWindowTextLength(app_hWnd)
buf = Space$(Length)
Length = GetWindowText(app_hWnd, buf, Length)
title = Left$(buf, Length)
' See if the title contains the TestFlex string.
If InStr(title, m_TestFlexString) <> 0 Then
' This is the one we want.
m_TestFlexHwnd = app_hWnd
' Stop searching.
EnumCallback = 0
Else
' Continue searching.
EnumCallback = 1
End If
End Function
因此,使用上述功能,您应该能够执行以下操作:
Dim saveAsHwnd as Long
call saveAsHwnd = FindWindowByPartialTitle("Save")
call SetForegroundWindo(saveAsHwnd)
别忘了也贴上 SetForegroundWindow:
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long