Search code examples
c#castinghandleintptr

Convert/Cast String (from a textbox) to IntPtr C#


I have a textbox where I want to input (manually) a Handle (https://i.sstatic.net/4Zzrt.png)

My problem: to get the value from the textbox I need to do this:

textBoxHandle.Text;

but when I initialize my Handle as IntPtr (handle), this doesn't work:

IntPtr h = new IntPtr(textBoxHandle.Text);

I have tried doing

(IntPtr) textBoxHandle.Text

And also many other options I've read around here like Marshal.StringToHGlobalAnsi Method but they don't work/ they change the content.

My question: how do I get an IntPtr (handle) from the string (with a Handle format) that is in the textbox?

EDIT: In the textbox I would write 0x00040C66 for instance.

The final code should be:

IntPtr hWnd = new IntPtr(0x00040C66);

But changing the IntPtr for the value from the textbox.

EDIT: My question was marked as duplicated (How can I convert an unmanaged IntPtr type to a c# string?) but it's not the same. It's not from IntPtr to String what I want. I need the opposite, from String to IntPtr.


Solution

  • You need to parse the string into an int or long first, then construct the IntPtr.

    IntPtr handle = new IntPtr(Convert.ToInt32(textBoxHandle.Text, 16));
    // IntPtr handle = new IntPtr(Convert.ToInt64(textBoxHandle.Text, 16));
    

    The second argument of Convert.ToInt32 and ToInt64 specifies the radix of the number and since you're parsing a hexadecimal number string, it needs to be 16.