문제

이 코드를 고려하십시오.

using Microsoft.Office.Interop.Word;

ApplicationClass _application = new ApplicationClass();

_application에 의해 시작된 winword.exe 프로세스에서 PID를 얻을 수 있습니까?

손상된 파일을 사용하면이 코드를 사용하여 ApplicationClass를 종료 할 수 없기 때문에 PID가 필요합니다.

_application.Quit(ref saveFile, ref missing, ref missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(_application);
GC.Collect();
GC.WaitForPendingFinalizers();

나는 winword.exe 프로세스를 검색하고 죽일 수 없습니다. 왜냐하면 나는 몇 가지를 가질 것이기 때문에 어떤 것을 죽일지 모르겠습니다. 각 ApplicationClass에 대해 PID를 얻을 수 있다면 올바른 winword.exe 프로세스를 죽일 수 있습니다.

도움이 되었습니까?

해결책

다음은 다음과 같습니다.

//Set the AppId
string AppId = ""+DateTime.Now.Ticks(); //A random title

//Create an identity for the app

this.oWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
this.oWordApp.Application.Caption = AppId;
this.oWordApp.Application.Visible = true;

while (GetProcessIdByWindowTitle(AppId) == Int32.MaxValue) //Loop till u get
{
    Thread.Sleep(5);
}

///Get the pid by for word application
this.WordPid = GetProcessIdByWindowTitle(AppId);

///You canh hide the application afterward            
this.oWordApp.Application.Visible = false;

/// <summary>
/// Returns the name of that process given by that title
/// </summary>
/// <param name="AppId">Int32MaxValue returned if it cant be found.</param>
/// <returns></returns>
public static int GetProcessIdByWindowTitle(string AppId)
{
   Process[] P_CESSES = Process.GetProcesses();
   for (int p_count = 0; p_count < P_CESSES.Length; p_count++)
   {
        if (P_CESSES[p_count].MainWindowTitle.Equals(AppId))
        {
                    return P_CESSES[p_count].Id;
        }
   }

    return Int32.MaxValue;
}

다른 팁

Word 파일에 약간의 오류가있을 수 있습니다. 결과적으로 메소드로 파일을 열면 Word.ApplicationClass.Documents.Open(), 대화 상자가 표시되며 프로세스가 중단됩니다.

사용 Word.ApplicationClass.Documents.OpenNoRepairDialog() 대신에. 문제가 해결되었습니다.

이를 얻는 일반적인 방법은 단어의 제목을 독특한 것으로 변경하고 (Enumwindows) 찾을 때까지 최상위 창 목록을 통해 뛰어 다니는 것입니다.

http://www.codekeep.net/snippets/7835116d-b254-466e-ae66-666e4fa3ea5e.aspx

///Return Type: DWORD->unsigned int
///hWnd: HWND->HWND__*
///lpdwProcessId: LPDWORD->DWORD*
[System.Runtime.InteropServices.DllImportAttribute( "user32.dll", EntryPoint = "GetWindowThreadProcessId" )]
public static extern int GetWindowThreadProcessId ( [System.Runtime.InteropServices.InAttribute()] System.IntPtr hWnd, out int lpdwProcessId );


private int _ExcelPID = 0;
Process _ExcelProcess;

private Application _ExcelApp = new ApplicationClass();
GetWindowThreadProcessId( new IntPtr(_ExcelApp.Hwnd), out _ExcelPID );
_ExcelProcess = System.Diagnostics.Process.GetProcessById( _ExcelPID );

...

_ExcelProcess.Kill();

안타깝게도 Application Class의 인스턴스를 Word 프로세스와 연관시키는 방법이 없습니다.

왜 단어의 인스턴스를 죽여야합니까? 모든 문서를 닫은 다음 그 인스턴스 사용을 중단하도록 요청할 수 없습니까? 결국 클래스에 대한 모든 참조를 제거하면 GC 차고 내려갑니다 com 섬기는 사람.

응용 프로그램을 시작하기 전에 실행중인 모든 워드 프로세스를 나열하고 응용 프로그램을 시작한 후 Word 프로세스 실행을 다시 나열하십시오. 두 번째 목록에서 발견되었고 첫 번째 목록에서 찾을 수없는 프로세스는 올바른 것입니다.

var oPL1 = from proc in Process.GetProcessesByName("WINWORD") select proc.Id;
var app = new Word.Application();

var oPL2 = from proc in Process.GetProcessesByName("WINWORD") select proc.Id;
var pid = (from p in oPL2 where !oPL1.Contains(p) select p).ToList()[0];

이 방법에는 명백한 타이밍 문제가 있지만 대부분의 시간을 확실하게 작동시키는 것은 내가 찾은 유일한 문제입니다.

enter code here  public void OpenWord(string Path, bool IsVisible)
    {

        MessageFilter.Register();
        object oMissing = Missing.Value;
        GUIDCaption = Guid.NewGuid().ToString();
        wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
        wordApp.Visible = IsVisible;
        wordApp.Caption = GUIDCaption;
        object oPath = Path;
        wordDoc = wordApp.Documents.Open(ref  oPath, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

    }
    /// <summary>
    /// 关闭文件
    /// </summary>
    public void CloseWord()
    {
        object oMissing = Missing.Value;
        GUIDCaption = "";
        if (null != wordDoc)
        {
            wordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
        }
        if (null != wordApp)
        {
            wordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
        }
        MessageFilter.Revoke();
        GC.Collect();
        KillwordProcess();

    }
    /// <summary>
    /// 结束word进程
    /// </summary>
    public void KillwordProcess()
    {
        try
        {
            Process[] myProcesses;
            //DateTime startTime;
            myProcesses = Process.GetProcessesByName("WINWORD");

            //通过进程窗口标题判断
            foreach (Process myProcess in myProcesses)
            {
                if (null != GUIDCaption && GUIDCaption.Length > 0 && myProcess.MainWindowTitle.Equals(GUIDCaption))
                {
                    myProcess.Kill();
                }
            }
            MessageFilter.Revoke();
        }
        catch (Exception e)
        {
            throw e;
        }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top