running compact framework code on desktop computer

434 views Asked by At

I made an application for Windows Compact Framework 3.5 , which appears to work fine.

After compilation a .exe file is created on my computer. Until recently, I could actually also run this exe file on my computer. (without the use of a simulator)

But recently I noticed that my application only runs on mobile devices. When I try to run it on my desktop computer I receive a strange error message which indicates that I should run my application with the [STAThread] directive for the Main() method.

However, for my mobile devices this is not necessary, everything works fine as is. In fact, I cannot even add the [STAThread] to the source code because the compact framework does not support it. Adding it causes compilation errors.

Unfortunately that's also the problem now. I would love to add some conditional code which evaluates if it's running on Windows CE or Windows Desktop. When it runs on desktop it should then start the code in STAThread mode. However, I cannot find a way to add this kind of code, because it doesn't compile. It always comes down to the point that the compiler does not know what STAThread is.

Is there a way or trick to handle this?

A good workaround for me, would be to compile it in a different way, perhaps by selecting a different target platform when I compile it for desktop computers. However, I am not able to do so currently. Any ideas ?

1

There are 1 answers

1
bvdb On BEST ANSWER

In summary the code only needs to run in STA state when it runs on a desktop computer. Furthermore the STA state isn't even available on a mobile device.

This is what I came up with:

    static void Main() 
    {
        Type type = typeof(Thread);
        MethodInfo methodInfo = type.GetMethod("SetApartmentState");

        if (methodInfo != null)
        {
            // full .net framework
            // --> requires STA apartmentstate

            Thread thread = new Thread(() => Run());
            methodInfo.Invoke(thread, new object[] { ApartmentState.STA });
            thread.Start();
            thread.Join();
        }
        else
        {
            // .net compact framework
            // --> needs no special attention (can run in MTA)
            Run();
        }
    }

Note: The Run() method above, is the one that starts the application.

Due to the fact that the code is written in Compact Framework, the apartment state cannot be set directly, simply because there is no setApartmentState method. But fortunately, it can be done using reflection, because the method will actually be available at runtime when (and only when) the code runs on the full .net framework.