使用Excel-2010,Visual-Studio-2013 Professional,
我试图以编程方式找出Excel-Workbook中出现鼠标单击(或者键盘快捷方式也可以接受)?我说服了几个想法,但是所有这些都表明了同样的问题:Excel-AddIn用于所有打开的Excel工作簿,并且在某种意义上弄乱了所需的信息,它确实给了我错误的鼠标来源 - 单击(或键盘快捷键单击)。它没有告诉我所需的原点窗口,但告诉我点击是从一个不活跃的窗口发生的!我真的不知道为什么下面的代码片段会返回任意工作簿 - 来源(但从来没有我需要的那个,这是我点击的一个窗口!)...
在哪个窗口中,使用相同的Excel-AddIn代码打开多个Excel工作簿的鼠标单击(或键盘快捷方式)发生器的最佳方法是什么?
这是我到目前为止所尝试的内容:
A)如here所示,全局键盘钩不是解决方案。
B)GetActiveWindow()
const int nChars = 256;
IntPtr handle1 = GetActiveWindow();
StringBuilder Buff1 = new StringBuilder(nChars);
if (GetWindowText(handle1, Buff1, nChars) > 0) {
MessageBox.Show(Buff1.ToString());
}
C)GetForegroundWindow()
const int nChars = 256;
IntPtr handle2 = GetForegroundWindow();
StringBuilder Buff2 = new StringBuilder(nChars);
if (GetWindowText(handle2, Buff2, nChars) > 0) {
MessageBox.Show(Buff2.ToString());
}
D)ApplicationIsActivated()
public static bool ApplicationIsActivated()
{
var activatedHandle = GetForegroundWindow();
if (activatedHandle == IntPtr.Zero) {
return false; // No window is currently activated
}
var procId = Process.GetCurrentProcess().Id;
int activeProcId;
GetWindowThreadProcessId(activatedHandle, out activeProcId);
MessageBox.Show(activeProcId.ToString());
MessageBox.Show(procId.ToString());
return activeProcId == procId;
}
以上代码片段需要导入:
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
static extern IntPtr GetActiveWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
[DllImport("user32.dll")]
static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport("user32.dll")]
static extern IntPtr GetFocus();
任何想法都赞赏!