无法获取进程的窗口句柄

时间:2017-01-02 21:16:19

标签: c# wpf exception process automation

我想做什么

我循环遍历可执行路径,为每个可执行文件启动一个进程,然后尝试检索每个进程的窗口句柄。然后我使用此窗口句柄调整大小或在屏幕上移动过程。

问题

大部分时间这都没有问题,但是我注意到如果我执行一个图像文件(例如.jpg)代码无法获取窗口句柄并抛出InvalidOperationException,那么我无法调整大小/移动窗口。

为什么我认为它会发生

一点点阅读告诉我这个过程正在使用dllhost.exe进程。从我到目前为止所读到的内容来看,在我看来权限仅限于此过程,因此无法完成我需要做的工作所需的属性。

是否有变通方法/解决方案

有没有人对此有任何解决方法?我想我可能需要创建一个自定义解决方案来检测我们是否真的可以获得窗口句柄,如果不是,我可以提示用户让他们知道。在这种特殊情况下,我可以让他们在不使用dllhost.exe的其他程序中打开可执行文件

例外的屏幕截图

Exceptions

守则

private Boolean executeProgram(string executionPath,
                                       int height,
                                       int width,
                                       int heightOffset,
                                       int widthOffset)
        {
            Boolean rtn = false;

            Process prs = new Process();

            IntPtr mWH = IntPtr.Zero;

            try
            {
                //TODO Need to create another process if process already exists, i.e if you start a media file default player
                //opens it, we need to ensure that another player is instantiated to play the new file
                prs.StartInfo.FileName = executionPath;

                prs.Start();

                //Move to this applications window after starting to allow the target window for manipulation.
                SwitchToThisWindow(thisApp, false);

                //Loop until a window handle has successfully be assigned, process executes too fast otherwise
                //and we will fail getting the window handle without this while loop.                   
                while(mWH == IntPtr.Zero)
                {
                    mWH = prs.MainWindowHandle;
                }

                if(MoveWindow(mWH, widthOffset, heightOffset, width, height, true))
                {
                    System.Windows.Forms.MessageBox.Show("Moved!");
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Not Moved!");
                }

            }
            catch (Exception ex)
            {
                string msg = "Error Encountered!" + Environment.NewLine;
                System.Windows.Forms.MessageBox.Show(msg + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                prs.Dispose();
            }             

            return rtn;
        }

异常消息

没有与此对象关联的进程

活动的最低数量的指导表示赞赏。谢谢。

0 个答案:

没有答案
相关问题