C# Win32 API 应用
C# Win32 API 應(yīng)用
1 創(chuàng)建進(jìn)程及獲取進(jìn)程的信息
部分代碼:?
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?+?"?"?+?"運(yùn)行成功");
}
else
{
MessageBox.Show(textBox1?+?"?"?+?"運(yùn)行失敗");
}
}
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 枚舉窗口,查看窗口信息和操作;
總結(jié)
以上是生活随笔為你收集整理的C# Win32 API 应用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。