与Microsoft Word一样,如果我们打开多个Word窗口,那么我们会发现它们位于一个名为WINWORD的进程下,其下有多个任务.
在Window 8.1 Pro的任务管理器中,我们可以右键单击它并通过End Task结束它.
我成功地使用流程名称来完成最终流程,但我无法从谷歌搜索中了解到在这种情况下如何在某些流程下杀死某些任务.
强调:我不是在问如何杀死这个过程.
过程[I] .Kill();
我成功杀死了指定的Word窗口
using System;
using System.Runtime.InteropServices;
namespace CloseTask
{
class Program
{
[DllImport("user32.dll")]
public static extern int FindWindow(string lpClassName,string lpWindowName);
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);
public const int WM_SYSCOMMAND = 0x0112;
public const int SC_CLOSE = 0xF060;
static void Main(string[] args)
{
closeWindow();
}
private static void closeWindow()
{
// retrieve the handler of the window of Word
// Class …Run Code Online (Sandbox Code Playgroud) 我正在使用Office互操作创建一个新的Word实例:
var word = Microsoft.Office.Interop.Word.Application();
word.Visible = true;
word.Activate;
Run Code Online (Sandbox Code Playgroud)
我可以像这样得到一个窗口句柄:
var wordHandle = Process.GetProcessesByName("winword")[0].MainWindowHandle;
Run Code Online (Sandbox Code Playgroud)
问题是代码的工作原理是假设没有其他Word运行实例.如果有多个,则无法保证它返回的句柄是针对我已启动的实例.我GetForegroundWindow在检测WindowActivate到来自我的对象的事件之后尝试使用但是这一切都在WPF应用程序中运行,该应用程序被设置为作为最顶层的窗口运行,所以我只获得了WPF窗口的句柄.有没有其他方法来获取我的单词实例的句柄?
我希望我的Word应用程序在自动化完成后进入前台.
Excel中的等效项是直接的 - Excel Application对象具有.Hwnd属性,您可以将其与Windows API结合使用:
SetForegroundWindow((IntPtr)excelApp.Hwnd);
Run Code Online (Sandbox Code Playgroud)
但是,Word应用程序没有.Hwnd属性.
我尝试在这个序列中使用Activate():
wordDoc.Activate();
wordApp.Activate();
Run Code Online (Sandbox Code Playgroud)
但这不起作用.
我已经看过使用应用程序名称查找进程,但可能有多个Word运行副本.
谢谢
乔