Process32FirstW always returns false

goose

Process32FirstW is suppose to return true when it finds process and return the first process in a PROCESSENTRY32W structure but it doesnt, so i cant enumerate it in Process32Next sadly. What is the reason it doesnt return true as a bool function? [([([( I have changed the struct deceleration )])])])]

        [StructLayout(LayoutKind.Sequential)]
        public struct PROCESSENTRY32W
        {
            public uint dwSize;
            public uint cntUsage;
            public uint th32ProcessID;
            public IntPtr th32DefaultHeapID;
            public uint th32ModuleID;
            public uint cntThreads;
            public uint th32ParentProcessID;
            public int pcPriClassBase;
            public uint dwFlags;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szExeFile;
        }; 
        [DllImport("kernel32.dll", EntryPoint = "CreateToolhelp32Snapshot")]
        public static extern IntPtr CreateToolhelp32SnapshotRtlMoveMemory(UInt32 dwFlagsdes, UInt32 th32ProcessID);

        [DllImport("kernel32", EntryPoint = "Process32FirstW", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool Process32FirstW(IntPtr hSnapshot, IntPtr lppe);

        [DllImport("kernel32", EntryPoint = "Process32Next")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool Process32Next(IntPtr hSnapshot, IntPtr lppe);

        [DllImport("kernel32", EntryPoint = "CloseHandle")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CloseHandle(IntPtr handle);

        public static Dictionary<int, Process> get_process_list()
        {
            //Dictionary<string, Process> returnable_processes_ = new Dictionary<string, Process>();
            Dictionary<int, Process> returnable_processes_ = new Dictionary<int, Process>();
            IntPtr HANLDE_Processes = CreateToolhelp32SnapshotRtlMoveMemory(2,0);

            PROCESSENTRY32W p32Iw = new PROCESSENTRY32W();
            p32Iw.dwSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(PROCESSENTRY32W));
            IntPtr p32IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(p32Iw));
            Marshal.StructureToPtr(p32Iw, p32IntPtr, false);
            bool blFirstProcess = Process32FirstW(HANLDE_Processes, p32IntPtr); // returns false no matter what?
            int x = Marshal.GetLastWin32Error();

            if(blFirstProcess)
            { 

                do
                {
                    Marshal.PtrToStructure(p32IntPtr, p32Iw);
                    int PID = (int) p32Iw.th32ProcessID;
                    returnable_processes_.Add(PID, new Process());

                } 
                while(Process32Next(HANLDE_Processes, p32IntPtr));
            }





            Marshal.FreeHGlobal(p32IntPtr);
            return returnable_processes_;
        }
Drake Wu

It's really a charset problem. You use the ***W version of api. The actual type of PROCESSENTRY32W.szExeFile is wchar_t, which is 2 bytes, so the structure size you passed is 260 bytes shorter(you can simply try p32Iw.dwSize + 260, Process32FirstW will return ture, if we are regardless of the subsequent execution). Fix the struct declaration and run the "C/C++ Programming" C# code.

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct PROCESSENTRY32 
   { 
      public uint dwSize; 
      public uint cntUsage; 
      public uint th32ProcessID; 
      public IntPtr th32DefaultHeapID; 
      public uint th32ModuleID; 
      public uint cntThreads; 
      public uint th32ParentProcessID; 
      public int pcPriClassBase; 
      public uint dwFlags; 
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)] public string szExeFile; 
    };

But according to the document, Marshal.StructureToPtr and Marshal.PtrToStructure are out of date and we should avoid using it. And this way of passing values through pointers is usually replaced by references in C#.

First, declare charset and reference parameters for Process32First and Process32Next

[DllImport("kernel32", EntryPoint = "Process32First", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32W lppe);

[DllImport("kernel32", EntryPoint = "Process32Next", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32W lppe);

Then, Pass the ref type of PROCESSENTRY32W:

bool blFirstProcess = Process32First(HANLDE_Processes, ref p32Iw); // returns false no matter what?
if (blFirstProcess)
{
   do
   {
      //Marshal.PtrToStructure(p32IntPtr, p32Iw);
      int PID = (int)p32Iw.th32ProcessID;
      returnable_processes_.Add(PID, new Process());
      Console.WriteLine(p32Iw.szExeFile);
   }
   while (Process32Next(HANLDE_Processes, ref p32Iw));
 }

Summarize, a minimal, compilable example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace ConsoleApp
{
    class Program
    {
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
         public struct PROCESSENTRY32W
        {
            public uint dwSize;
            public uint cntUsage;
            public uint th32ProcessID;
            public IntPtr th32DefaultHeapID;
            public uint th32ModuleID;
            public uint cntThreads;
            public uint th32ParentProcessID;
            public int pcPriClassBase;
            public uint dwFlags;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szExeFile;
        };
        [DllImport("kernel32.dll", EntryPoint = "CreateToolhelp32Snapshot")]
        public static extern IntPtr CreateToolhelp32SnapshotRtlMoveMemory(UInt32 dwFlagsdes, UInt32 th32ProcessID);

        [DllImport("kernel32", EntryPoint = "Process32First", SetLastError = true, CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32W lppe);

        [DllImport("kernel32", EntryPoint = "Process32Next", CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32W lppe);

        [DllImport("kernel32", EntryPoint = "CloseHandle")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CloseHandle(IntPtr handle);
        public static Dictionary<int, Process> get_process_list()
        {
            //Dictionary<string, Process> returnable_processes_ = new Dictionary<string, Process>();
            Dictionary<int, Process> returnable_processes_ = new Dictionary<int, Process>();
            IntPtr HANLDE_Processes = CreateToolhelp32SnapshotRtlMoveMemory(2, 0);

            PROCESSENTRY32W p32Iw = new PROCESSENTRY32W();
            int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(PROCESSENTRY32W));
            p32Iw.dwSize = Convert.ToUInt32(size);
            //IntPtr p32IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(p32Iw));
            //Marshal.StructureToPtr(p32Iw, p32IntPtr, false);
            bool blFirstProcess = Process32First(HANLDE_Processes, ref p32Iw); // returns false no matter what?
            int x = Marshal.GetLastWin32Error();

            if (blFirstProcess)
            {

                do
                {
                    int PID = (int)p32Iw.th32ProcessID;
                    returnable_processes_.Add(PID, new Process());
                    Console.WriteLine(p32Iw.szExeFile);

                }
                while (Process32Next(HANLDE_Processes, ref p32Iw));
            }
            return returnable_processes_;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            get_process_list();
            Console.ReadKey();
        }
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive