检查焦点是否设置为excel cell

时间:2012-12-24 12:50:38

标签: c# excel excel-vba vsto vba

我正在研究VSTO项目。我需要在Excel vsto项目中检测输入焦点。

我想检查焦点是在excel单元格上还是在其他excel组件上,例如查找对话框,文档操作窗格或任何其他excel内置对话框。

这可以检测吗?

Please refer screen shot

如屏幕截图所示,我想知道输入焦点是否设置为excel cell?

2 个答案:

答案 0 :(得分:3)

这将获得活动窗口(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

答案 1 :(得分:0)

你需要做这样的事情:

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;
}