ProcessID(终止进程)c#没有返回值

时间:2016-12-07 07:34:34

标签: c# process

我正在尝试根据进程ID干净地关闭Excel,Powerpoint或word进程。

工作流: 目的是我们有2个文件夹。每个屏幕1个。我们正在使用双屏幕设置,并希望在1页上显示单词并在另一页上表现出色。这就像魅力一样。当其中一个文件被编辑时。或者他们将另一个文件放在其中一个文件夹中。我要求程序杀死进程。并重新加载文件(新文件)我用观察者事件处理来完成这个。

所以我在程序启动时填写一个包含所有processID的列表(Powerpoint / excel / word)

///list of all CREATED processes ( word / excel / powerpoint + adds in the list
public static List<int> pids = new List<int>();
p.Start();
pids.Add(p.Id);

当变化发生时。我启动了一个方法,检查Pids列表中的进程是否与主机上运行的所有进程的进程列表中的1个进程匹配。

Process[] runningProcs = Process.GetProcesses();

foreach (Process proc in runningProcs) {
  foreach (int pid in pids) {
       if (pid == proc.Id) {
           TryKillProcessByMainWindowHwnd(pid);
           }
   }
}

这完美无缺。因为它仅在匹配时返回true,并且它通过processid传递。

我通过此声明导入DLL

[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

我通过这里回忆这个方法

 public static bool TryKillProcessByMainWindowHwnd(int hWnd) {

        uint processID;

        GetWindowThreadProcessId((IntPtr)hWnd, out processID);

        if (processID == 0) return false;

        try {

            Process.GetProcessById((int)processID).CloseMainWindow();

        }
        catch (ArgumentException) {
            return false;
        }
        catch (Win32Exception) {
            return false;
        }
        catch (NotSupportedException) {
            return false;
        }
        catch (InvalidOperationException) {
            return false;
        }
        return true;
    }
///Watcher event service that checks both subfolders for changes
       public static void watch(string scherm)
    {
        watcher.Path = "C:\\test\\";
        watcher.IncludeSubdirectories = true;
        watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Filter = "*.*";
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;
    }

/// Onchanged event handling
public static void OnChanged(object source, FileSystemEventArgs e) {
  watcher.EnableRaisingEvents = false;
///This code first deletes all processes and then tries to clean up the     folder (method explains beneath this topic)
  ReleaseOlderFiles();
///checkfolder launches the new edited files. + screen allocation
  checkFolder();
  Debug.WriteLine("Onchanged fired!");
  watcher.EnableRaisingEvents = true;
}

///ReleaseOlderFilesMethod
      public static void ReleaseOlderFiles()
    {

        string[] files = Directory.GetFiles(scherm1);

        foreach (string file in files)
        {
            FileInfo fi = new FileInfo(file);

            if (fi.LastAccessTime < DateTime.Now.AddMilliseconds(-5000))
            {
                try
                {
                    Process[] runningProcs = Process.GetProcesses();

                    foreach (Process proc in runningProcs)
                    {
                        foreach (int pid in pids)
                        {

                            if (pid == proc.Id)
                            {
                                TryKillProcessByMainWindowHwnd(pid);
                            }
                        }
                    }
                }

                catch { }
                fi.Delete();
            }
}

每次使用Excel / Powerpoint / Word中的hWnd填充hWnd变量。 由于某些奇怪的原因,processID始终返回0值。所以对方法的调用似乎没有输出任何东西

我尝试了一切,但我没看到什么? 在此先感谢,这将是我的项目最终确定的一个重要帮助!

1 个答案:

答案 0 :(得分:0)

找到解决方案! 就那么简单 ! 正如@Maksim Simkin所说。只需更改processID即可。像这样:

 public static bool TryKillProcessByMainWindowHwnd(int processID)
    {

        try
        {
            Process.GetProcessById((int)processID).CloseMainWindow();
        }
        catch (ArgumentException)
        {
            return false;
        }
        catch (Win32Exception)
        {
            return false;
        }
        catch (NotSupportedException)
        {
            return false;
        }
        catch (InvalidOperationException)
        {
            return false;
        }
        return true;
    }

在我的方法中删除文件。我需要为线程添加一点睡眠。

        public static void ReleaseOlderFiles()
    {

        string[] files = Directory.GetFiles(scherm1);

        foreach (string file in files)
        {
            FileInfo fi = new FileInfo(file);

            if (fi.LastAccessTime < DateTime.Now.AddMilliseconds(-5000))
            {
                try
                {
                    Process[] runningProcs = Process.GetProcesses();

                    foreach (Process proc in runningProcs)
                    {
                        foreach (int pid in pids)
                        {

                            if (pid == proc.Id)
                            {
                                TryKillProcessByMainWindowHwnd(pid);
                            }
                        }
                    }
                }

                catch { }
                Thread.Sleep(500);
                fi.Delete();
            }

        }
    }

就像魅力一样!