1 创建进程及获取进程的信息
部分代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace CreateProcess
{
public partial class Form1 : Form
{
[DllImport("Kernel32.dll", CharSet = CharSet.Ansi)]
public static extern bool CreateProcess(StringBuilder lpApplicationName, StringBuilder lpCommandLine,
SECURITY_ATTRIBUTES lpProcessAttributes,
SECURITY_ATTRIBUTES lpThreadAttributes,
bool bInheritHandles,
int dwCreationFlags,
StringBuilder lpEnvironment,
StringBuilder lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
ref PROCESS_INFORMATION lpProcessInformation
);
[DllImport("Kernel32.dll", CharSet = CharSet.Ansi)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("Kernel32.dll", CharSet = CharSet.Ansi)]
public static extern bool TerminateProcess(IntPtr hProcess, uint ExitCode);
[StructLayout(LayoutKind.Sequential)]
public class SECURITY_ATTRIBUTES
{
public int nLength;
public string lpSecurityDescriptor;
public bool bInheritHandle;
}
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public int cb;
public string lpReserved;
public string lpDesktop;
public int lpTitle;
public int dwX;
public int dwY;
public int dwXSize;
public int dwYSize;
public int dwXCountChars;
public int dwYCountChars;
public int dwFillAttribute;
public int dwFlags;
public int wShowWindow;
public int cbReserved2;
public byte lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
STARTUPINFO sInfo = new STARTUPINFO();
PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ope = new OpenFileDialog();
ope.ShowDialog();
textBox1.Text = ope.FileName;
}
private void button2_Click(object sender, EventArgs e)
{
bool ret;
//StringBuilder sbCommand = new StringBuilder(1000);
//sbCommand.Append(sCommand);
StringBuilder sbexeFile = new StringBuilder();
sbexeFile.Append(textBox1.Text);
try
{
ret=CreateProcess(sbexeFile, null, null, null, false, 0, null, null,
ref sInfo, ref pInfo);
if (ret == true)
{
MessageBox.Show(textBox1 + " " + "运行成功");
}
else
{
MessageBox.Show(textBox1 + " " + "运行失败");
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
TerminateProcess(pInfo.hProcess, 0);
CloseHandle(pInfo.hProcess);
CloseHandle(pInfo.hThread);
}
}
}
2 枚举窗口,查看窗口信息和操作;