A window handle sometimes of type int
and other times of type IntPtr
int
example:
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);
IntPtr
example:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam);
I don't seem to be able to convert/cast from one to the other.
When I try this.ProcessID = GetWindowThreadProcessId(windowHandle.ToInt32(),0)
I get an error cannot implicitly convert from uint to int
I think that error
cannot implicitly convert from uint to int
refers to=
statement. The fieldthis.ProcessID
isint
, butGetWindowThreadProcessId
returnsuint
.Try this
I was getting "Arithmetic operation resulted in an overflow", whenever I was:
instead of that:
The
SendMessage
signature isor this
Don't exchange
int
andIntPtr
. They are nearly equivalent only at 32 bits (equal in size). At 64 bits anIntPtr
is nearly equivalent to along
(equal in size)The
GetWindowThreadProcessId
signature isor
In this case, a
ref
or aout
to "something" are managed references to something, so they are internally converted toIntPtr
when passed to Native API. Soout uint
is, from the point of view of the Native API, equivalent toIntPtr
.Explanation: what is important is that the "length" of the parameters is the correct one.
int
anduint
are equal for the called API. And a 32bitIntPtr
is the same too.Note that some types (like
bool
andchar
) have special handling by the marshaler.You shouldn't EVER convert an
int
to anIntPtr
. Keep it as anIntPtr
and live happy. If you have to make some math operations not supported byIntPtr
, uselong
(it's 64 bits, so until we will have Windows 128, there won't be any problem :-) ).