C# 尝试获取c中VBA MsgBox的内容时出错#
我试图从word模板截取VB MsgBoxes并自动单击它们。此代码插入到C#Winforms应用程序中的一个类中,C# 尝试获取c中VBA MsgBox的内容时出错#,c#,C#,我试图从word模板截取VB MsgBoxes并自动单击它们。此代码插入到C#Winforms应用程序中的一个类中,KillMbox()只需单击该表单中的按钮即可运行。 我在VisualStudio的调试模式下尝试了这个应用程序,代码运行得非常好,截获了VBA消息框 但是,在我关闭调试模式并重试后,我收到未知模块中发生了类型为“System.NullReferenceException”的未处理异常。对象引用未设置为对象的实例。 错误出现在GetWindowText(txtHandle,sb,l
KillMbox()
只需单击该表单中的按钮即可运行。
我在VisualStudio的调试模式下尝试了这个应用程序,代码运行得非常好,截获了VBA消息框
但是,在我关闭调试模式并重试后,我收到未知模块中发生了类型为“System.NullReferenceException”的未处理异常。对象引用未设置为对象的实例。
错误出现在GetWindowText(txtHandle,sb,len+1)行代码>。
我曾在不同的计算机上以调试模式尝试过该应用程序,但它有相同的问题,只是第一次工作
在内部版本中,应用程序刚刚崩溃,接收到的应用程序名称已停止工作。
[DllImport("user32.dll")] static extern int FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")] static extern int SendMessage(int hWnd, int wMsg, int wParam, int lParam);
[DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern int GetWindowTextLength(IntPtr hWnd);
public static void KillMbox()
{
for (int h = 0; h == 0;)
{
Thread.Sleep(1000);
h = FindWindow(null, "Microsoft Word");
if (h != 0)
{
IntPtr hAsIntPtr = new IntPtr(h);
IntPtr txtHandle = FindWindowEx(hAsIntPtr, IntPtr.Zero, "Static", null);
int len = GetWindowTextLength(txtHandle);
StringBuilder sb = new StringBuilder();
GetWindowText(txtHandle, sb, len + 1);
SendMessage(h, 16, 0, 0);
MessageBox.Show(sb.ToString());
}
}
}
这是与代码相关的错误还是bug?谢谢大家! 当word文档中没有msgbox时,为什么不尝试执行代码呢。我确信会发生错误,因为FindWindowEx返回null。还要阅读正在执行的PinVoke的文档,您必须在声明put:SetLastError=true中处理它们可能返回的错误,然后使用GetLastError()获取可能发生的错误的详细信息GetWindowText()调用与缓冲区大小有关。由此产生的内存损坏可能会导致各种随机的古怪错误。继续使用StringBuilder sb=新StringBuilder(len+1);对于这种代码,强烈支持System.Windows.Automation。