Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 660
сами J.D. Avatar asked Jul 14 '15 17:07

сами J.D.


People also ask

How do I cast a string to a class object in C#?

Deserialization is the process of parsing a string into an object of a specific type. The JsonSerializer. Deserialize() method converts a JSON string into an object of the type specified by a generic type parameter.

Can you cast a string to an int in C#?

Like other programming languages, in C# we can convert string to int. There are three ways to convert it and they are as follows: Using the Parse Method. Using the TryParse Method.


1 Answers

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.

like image 118
cbr Avatar answered Oct 17 '22 06:10

cbr