如何检测在哪个Excel工作簿被点击?

使用Excel-2010,Visual-Studio-2013 Professional,

我试图找出编程方式,其中Excel的工作簿鼠标单击发生(或键盘快捷方式发生也将是可以接受的)? 有几个想法我说服了,但他们都performance出同样的问题:所使用的Excel-AddIn会得到执行所有打开的Excel工作簿和混淆了所需的信息,因为它确实给了我错误的鼠标起源点击(或键盘快捷方式点击)。 它不告诉我所需的原点窗口,但告诉我,点击发生在一个非活跃的窗口! 我真的不知道为什么下面的代码片段返回任意的工作簿的起源(但从来没有我需要的,这是一个窗口,我点击里面!)…

什么是最好的方法来告诉从哪个窗口中鼠标点击(或键盘快捷方式)发生有几个Excel的工作簿打开使用相同的Excel-AddIn代码?

这是我到目前为止所尝试的:

A)如此处所见,全局键盘钩子不是解决scheme。

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(); 

任何想法赞赏!