我正在从事 VSTO 项目。我需要检测 Excel vsto 项目中的输入焦点。
我想检查焦点是在 excel 单元格上还是在其他 excel 组件上,如查找对话框、文档操作窗格或任何其他 excel 内置对话框。
这可以检测吗?
如屏幕截图所示,我想知道输入焦点是否设置为 Excel 单元格?
这将获得活动窗口的标题(vba)
Option Explicit
Private Declare Function GetActiveWindow Lib "User32.dll" () As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Function ActiveWindowName()
Dim hWnd As Long
Dim lngRet As Long
Dim strText As String
hWnd = GetActiveWindow()
strText = String(100, Chr(0))
lngRet = GetWindowText(hWnd, strText, 100)
ActiveWindowName=strText
End Function
它将返回活动窗口上的标题,但我假设 100 个字符的长度就足够了。
此代码应提供一个返回当前标题并正确调整长度的函数。(我目前没有安装 c#,所以无法测试):
[DllImport("user32.dll")]
static extern IntPtr GetActiveWindow();
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
public static string GetActiveWindowText()
{
IntPtr hWnd = GetActiveWindow();
// Allocate correct string length first
int length = GetWindowTextLength(hWnd);
StringBuilder sb = new StringBuilder(length + 1);
GetWindowText(hWnd, sb, sb.Capacity);
return sb.ToString();
}
然后,您应该能够测试该字符串以查看它包含的内容。在 VBA 示例中,=ActiveWindowName()
输入A1返回Microsoft Excel - Book1
你需要做这样的事情:
private bool CheckInputisinExcelCell()
{
Microsoft.Office.Core.CommandBarControl cmdEdited;
cmdEdited=YourExcelApplicationobject.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton, 23, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
return cmdEdited.Enabled;
}