Click to See Complete Forum and Search --> : Casting problem.


DennisWoo
November 29th, 2005, 08:59 AM
Environment: XP Pro SP2, VS.Net2003

I am setting up some context menu items that have shortcut keys associated to them. The shortcut keys are: Shortcut::CtrlShift0 to Shortcut::ChrlShift9. This how I implement it:

for( i=0 ; i<10 ; ++i )
{
miShortcuts[i]->Index = i ;
miShortcuts[i]->Text = String::Concat(S"Shortcut ", i.ToString() ) ;
miShortcuts[i]->Shortcut = static_cast<Shortcut>(*dynamic_cast<Shortcut *>(Enum::Parse(__typeof(Shortcut), String::Concat(S"CtrlShift",i.ToString())))) ;
miShortcuts[i]->Click += new System::EventHandler( this, MenuItem_Shortcut_Click ) ;
}


When I compiled it, I got this error:


error C2440: 'static_cast' : cannot convert from 'System::Enum' to 'System::Windows::Forms::Shortcut'


I have tried many things but I keep ending with similar error messages. Your help is appreciated.

Thanks!:cool:

Dennis

NoHero
November 29th, 2005, 09:27 AM
As far as I know this conversation you are trying to make needs unboxing: Since Enum::Parse() returns an Object* and you require a __value type. Here is an example on unboxing:

#using <mscorlib.dll>
using namespace System;
__value struct V { int i; };

int main ( void )
{
V v = {10};
Object* o = __box(v); // copy value to runtime heap
V v2 = *dynamic_cast<__box V*>(o); // copy back from runtime heap
}

So you need something like:

miShortcuts[i]->Shortcut = *dynamic_cast<__box Shortcut *>(Enum::Parse(__typeof(Shortcut), String::Concat(S"CtrlShift",i.ToString())));

DennisWoo
November 29th, 2005, 10:06 AM
Hi NoHero,

This works perfectly! As far as I am concerned, you are my hero of the day! I am glad to learn anothing thing about this boxing stuffs. I wonder if it is easier in VS2005 because soon enough I will be updating my codes to that.

Thanks a million! Have a great day!

Dennis

As far as I know this conversation you are trying to make needs unboxing: Since Enum::Parse() returns an Object* and you require a __value type. Here is an example on unboxing:

#using <mscorlib.dll>
using namespace System;
__value struct V { int i; };

int main ( void )
{
V v = {10};
Object* o = __box(v); // copy value to runtime heap
V v2 = *dynamic_cast<__box V*>(o); // copy back from runtime heap
}

So you need something like:

miShortcuts[i]->Shortcut = *dynamic_cast<__box Shortcut *>(Enum::Parse(__typeof(Shortcut), String::Concat(S"CtrlShift",i.ToString())));