遍历系统进程后,使用OpenProcess打开返回错误码87
我需要遍历系统进程,找到特定的进程句柄后执行某些操作,但是用CreateToolhelp32Snapshot遍历后,OpenProcess返回的进程句柄0,打印出来的错误编码为87,意思是“参数错误”,换了好几个参数都不行,卡住这里,不知道怎么办了。求救!
IntPtr hWndParent;
IntPtr handle = ToolHelp.CreateToolhelp32Snapshot(0x2, 0);
if ((int)handle > 0)
{
ToolHelp.ProcessEntry32 pe32 = new ToolHelp.ProcessEntry32();
pe32.dwSize = Marshal.SizeOf(pe32);
int bMore = ToolHelp.Process32First(handle, ref pe32);
while (bMore == 1)
{
if ("uedit32.exe" == pe32.szExeFile)
{
hWndParent = (IntPtr)ToolHelp.OpenProcess(ToolHelp.PROCESS_QUERY_INFORMATION | ToolHelp.PROCESS_VM_READ, false, pe32.th32ProcessID);
//打印出来的错误编码为87
Console.WriteLine("LastError:" + ToolHelp.GetLastError());
break;
}
bMore = ToolHelp.Process32Next(handle, ref pe32);
}
ToolHelp.CloseHandle(handle);
}
--------------------编程问答-------------------- 顶,没有人知道啊? --------------------编程问答-------------------- http://blog.163.com/kunkun0921@126/blog/static/169204332201282593152985/
public class ToolHelp
{
public const long PROCESS_ALL_ACCESS = 0x1F0FFF;
public const long PROCESS_QUERY_INFORMATION = 0x400;
public const long PROCESS_VM_READ = 0x10;
[DllImport("KERNEL32.DLL")]
public static extern IntPtr CreateToolhelp32Snapshot(int flags, int processid);
[DllImport("KERNEL32.DLL")]
public static extern int CloseHandle(IntPtr handle);
[DllImport("KERNEL32.DLL")]
public static extern int Process32First(IntPtr handle, ref ProcessEntry32 pe);
[DllImport("KERNEL32.DLL")]
public static extern int Process32Next(IntPtr handle, ref ProcessEntry32 pe);
[DllImport("KERNEL32.DLL")]
public static extern int GetLastError();
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern IntPtr GetCurrentProcess();
/// <summary>
/// 打开一个已存在的进程对象,并返回进程的句柄
/// </summary>
/// <param name="dwDesiredAccess">渴望得到的访问权限(标志)</param>
/// <param name="bInheritHandle">是否继承句柄</param>
/// <param name="dwProcessId">进程标示符</param>
/// <returns></returns>
[DllImport("kernel32.dll")]
public static extern int OpenProcess(long dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[StructLayout(LayoutKind.Sequential)]
public struct ProcessEntry32
{
public int dwSize;// 结构大小;
public int cntUsage;// 此进程的引用计数;
public int th32ProcessID; // 进程ID;
public IntPtr th32DefaultHeapID; // 进程默认堆ID;
public int th32ModuleID; // 进程模块ID;
public int cntThreads; // 此进程开启的线程计数;
public int th32ParentProcessID; // 父进程ID;
public int pcPriClassBase; // 线程优先权;
public int dwFlags; // 保留;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szExeFile;// 进程全名;
}
}
对照着找找问题 --------------------编程问答--------------------
就是看了这篇文章后才写出来的代码,我去掉了下面几行代码,貌似没什么作用。
--------------------编程问答-------------------- 顶一下,离成功仅一步之遥了。
IntPtr temp = Marshal.AllocHGlobal((int)pe32.dwSize);
Marshal.StructureToPtr(pe32, temp, true);
ProcessEntry32 pe = (ProcessEntry32)Marshal.PtrToStructure(temp, typeof(ProcessEntry32));
Marshal.FreeHGlobal(temp);
补充:.NET技术 , C#