7

I have a textbox where I want to input (manually) a Handle (https://i.stack.imgur.com/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.

Community
  • 1
  • 1
сами J.D.
  • 483
  • 2
  • 5
  • 19

1 Answers1

11

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.

cbr
  • 12,563
  • 3
  • 38
  • 63
  • Thanks, this sorted out my problem :) I didn't know a previous conversion to Int32 plus the radix was needed! – сами J.D. Jul 14 '15 at 18:06
  • @самиJ.D. Glad to hear that! Be sure to also look into [`Int32.Parse`](https://msdn.microsoft.com/en-us/library/system.int32.parse.aspx), [`Int32.TryParse`](https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx) and the [difference between Int32.Parse and Convert.ToInt32](http://stackoverflow.com/a/199484/996081). – cbr Jul 14 '15 at 18:08