Vb를 사용하여 프로세스를 종료하려면 어떻게 해야 합니까?NET 또는 C#?
사용자가 이미 마이크로소프트 워드를 열었는지 확인해야 하는 시나리오가 있습니다.만약 그가 그랬다면, 나는 윈워드를 죽여야만 합니다.exe 프로세스를 수행하고 내 코드를 계속 실행합니다.
vb.net 이나 c#을 사용하여 프로세스를 죽이는 간단한 코드를 가진 사람이 있습니까?
시스템을 사용할 수 있습니다.진단.과정.킬 메소드.시스템을 사용하여 원하는 프로세스를 얻을 수 있습니다.진단.성공.이름별로 프로세스를 가져옵니다.
예제는 이미 여기에 게시되었지만 .exe가 아닌 버전이 더 잘 작동했기 때문에 다음과 같은 것이 있습니다.
foreach ( Process p in System.Diagnostics.Process.GetProcessesByName("winword") )
{
try
{
p.Kill();
p.WaitForExit(); // possibly with a timeout
}
catch ( Win32Exception winException )
{
// process was terminating or can't be terminated - deal with it
}
catch ( InvalidOperationException invalidException )
{
// process has already exited - might be able to let this one go
}
}
당신은 아마도 당신을 상대할 필요가 없을 것입니다.NotSupportedException
이는 프로세스가 원격이라는 것을 의미합니다.
Word 프로세스를 완전히 삭제하는 것은 가능하지만(다른 답변 중 일부 참조), 완전히 무례하고 위험합니다. 사용자가 열려 있는 문서에서 저장하지 않은 중요한 변경사항이 있으면 어떻게 합니까?오래된 임시 파일은 말할 것도 없고, 이것이 남길 것은...
이것은 아마도 이와 관련하여 당신이 할 수 있는 한입니다(VB).NET):
Dim proc = Process.GetProcessesByName("winword")
For i As Integer = 0 To proc.Count - 1
proc(i).CloseMainWindow()
Next i
이렇게 하면 열려 있는 모든 Word 창이 순서대로 닫힙니다(해당되는 경우 사용자에게 작업 내용을 저장하도록 요청).물론 이 시나리오에서는 사용자가 언제든지 '취소'를 클릭할 수 있으므로 이 경우도 처리할 수 있어야 합니다("모든 Word 인스턴스를 닫으십시오. 그렇지 않으면 계속할 수 없습니다..." 대화 상자를 표시하는 것이 좋습니다).
다음은 모든 Word Process를 삭제하는 방법에 대한 쉬운 예입니다.
Process[] procs = Process.GetProcessesByName("winword");
foreach (Process proc in procs)
proc.Kill();
Word 프로세스가 실행 중인지 확인하고 사용자에게 종료를 요청한 다음 앱에서 '계속' 버튼을 클릭하면 보안 문제를 무시하고 훨씬 더 중요한 응용 프로그램을 만들 수 있습니다.이것은 많은 설치 관리자들이 취하는 접근 방식입니다.
private bool isWordRunning()
{
return System.Diagnostics.Process.GetProcessesByName("winword").Length > 0;
}
물론, 당신은 당신의 앱에 GUI가 있을 때만 이것을 할 수 있습니다.
public bool FindAndKillProcess(string name)
{
//here we're going to get a list of all running processes on
//the computer
foreach (Process clsProcess in Process.GetProcesses()) {
//now we're going to see if any of the running processes
//match the currently running processes by using the StartsWith Method,
//this prevents us from incluing the .EXE for the process we're looking for.
//. Be sure to not
//add the .exe to the name you provide, i.e: NOTEPAD,
//not NOTEPAD.EXE or false is always returned even if
//notepad is running
if (clsProcess.ProcessName.StartsWith(name))
{
//since we found the proccess we now need to use the
//Kill Method to kill the process. Remember, if you have
//the process running more than once, say IE open 4
//times the loop thr way it is now will close all 4,
//if you want it to just close the first one it finds
//then add a return; after the Kill
try
{
clsProcess.Kill();
}
catch
{
return false;
}
//process killed, return true
return true;
}
}
//process not found, return false
return false;
}
트레이 앱에서 엑셀과 워드 인터럽트를 청소해야 했습니다.따라서 이 간단한 방법은 일반적으로 프로세스를 죽입니다.
이것은 일반적인 예외 처리기를 사용하지만 다른 답변에 명시된 것처럼 여러 예외에 대해 쉽게 분할할 수 있습니다.로깅으로 인해 잘못된 긍정이 많이 생성되면 이 작업을 수행할 수 있습니다(이미 살해된 항목을 죽일 수 없음).하지만 지금까지 guid (일하는 농담).
/// <summary>
/// Kills Processes By Name
/// </summary>
/// <param name="names">List of Process Names</param>
private void killProcesses(List<string> names)
{
var processes = new List<Process>();
foreach (var name in names)
processes.AddRange(Process.GetProcessesByName(name).ToList());
foreach (Process p in processes)
{
try
{
p.Kill();
p.WaitForExit();
}
catch (Exception ex)
{
// Logging
RunProcess.insertFeedback("Clean Processes Failed", ex);
}
}
}
그때는 이렇게 불렀습니다.
killProcesses((new List<string>() { "winword", "excel" }));
다음과 같은 방법으로 작동합니다.
foreach ( Process process in Process.GetProcessesByName( "winword" ) )
{
process.Kill();
process.WaitForExit();
}
프로세스가 실행 중인지 여부를 감지하고 사용자에게 프로세스를 수동으로 닫으라고 말하는 것이 더 효과적이고 안전하며 예의 바른 방법입니다.물론 시간 제한을 추가하고 프로세스를 종료할 수도 있습니다. 만약 그들이 사라지면...
워드 파일 2개를 열었어요.이제 프로그래밍 방식으로 vb.net 런타임을 통해 다른 워드 파일을 엽니다. 3.프로그래밍 방식으로 두 번째 프로세스를 단독으로 종료하고 싶습니다. 4. 첫 번째 프로세스를 종료하지 마십시오.
.
public partial class Form1 : Form
{
[ThreadStatic()]
static Microsoft.Office.Interop.Word.Application wordObj = null;
public Form1()
{
InitializeComponent();
}
public bool OpenDoc(string documentName)
{
bool bSuccss = false;
System.Threading.Thread newThread;
int iRetryCount;
int iWait;
int pid = 0;
int iMaxRetry = 3;
try
{
iRetryCount = 1;
TRY_OPEN_DOCUMENT:
iWait = 0;
newThread = new Thread(() => OpenDocument(documentName, pid));
newThread.Start();
WAIT_FOR_WORD:
Thread.Sleep(1000);
iWait = iWait + 1;
if (iWait < 60) //1 minute wait
goto WAIT_FOR_WORD;
else
{
iRetryCount = iRetryCount + 1;
newThread.Abort();
//'-----------------------------------------
//'killing unresponsive word instance
if ((wordObj != null))
{
try
{
Process.GetProcessById(pid).Kill();
Marshal.ReleaseComObject(wordObj);
wordObj = null;
}
catch (Exception ex)
{
}
}
//'----------------------------------------
if (iMaxRetry >= iRetryCount)
goto TRY_OPEN_DOCUMENT;
else
goto WORD_SUCCESS;
}
}
catch (Exception ex)
{
bSuccss = false;
}
WORD_SUCCESS:
return bSuccss;
}
private bool OpenDocument(string docName, int pid)
{
bool bSuccess = false;
Microsoft.Office.Interop.Word.Application tWord;
DateTime sTime;
DateTime eTime;
try
{
tWord = new Microsoft.Office.Interop.Word.Application();
sTime = DateTime.Now;
wordObj = new Microsoft.Office.Interop.Word.Application();
eTime = DateTime.Now;
tWord.Quit(false);
Marshal.ReleaseComObject(tWord);
tWord = null;
wordObj.Visible = false;
pid = GETPID(sTime, eTime);
//now do stuff
wordObj.Documents.OpenNoRepairDialog(docName);
//other code
if (wordObj != null)
{
wordObj.Quit(false);
Marshal.ReleaseComObject(wordObj);
wordObj = null;
}
bSuccess = true;
}
catch
{ }
return bSuccess;
}
private int GETPID(System.DateTime startTime, System.DateTime endTime)
{
int pid = 0;
try
{
foreach (Process p in Process.GetProcessesByName("WINWORD"))
{
if (string.IsNullOrEmpty(string.Empty + p.MainWindowTitle) & p.HasExited == false && (p.StartTime.Ticks >= startTime.Ticks & p.StartTime.Ticks <= endTime.Ticks))
{
pid = p.Id;
break;
}
}
}
catch
{
}
return pid;
}
언급URL : https://stackoverflow.com/questions/116090/how-do-i-kill-a-process-using-vb-net-or-c
'sourcecode' 카테고리의 다른 글
SDK iOS 8.0의 제품 유형 Unit Test Bundle에 대한 코드 서명 필요 (0) | 2023.05.08 |
---|---|
여러 열에서 DISTINCT를 선택하려면 어떻게 해야 합니까? (0) | 2023.05.08 |
각도 CLI 오류:serve 명령을 Angular 프로젝트에서 실행해야 하지만 프로젝트 정의를 찾을 수 없습니다. (0) | 2023.05.08 |
'로컬 시스템' 계정과 '네트워크 서비스' 계정의 차이점은 무엇입니까? (0) | 2023.05.08 |
VB의 Null 검사입니다. (0) | 2023.05.08 |