Pregunta

Since I am writing a program that will eventually run on Windows and Linux environment compiled from the same project files, I wanted to test and see how well the Operating System directives are. So, I wrote a sample code. The code seems to run unexpectedly or it just my imagination.

Here is the code:

method MainForm.ControlBtn_Click(sender: System.Object; e: System.EventArgs);
begin
  {$IFDEF linux}
    MessageBox.Show('This is Linux. Horay!!!', 'mypro',MessageBoxButtons.yesno);
  {$ENDIF}

  {$IFDEF WIN32}
    MessageBox.Show('This is Win32. Horay!!!', 'mypro',MessageBoxButtons.yesno);
  {$ENDIF}

  {$IFDEF CLR}
    MessageBox.Show('This is .NET Framework. Horay!!!', 'mypro',MessageBoxButtons.yesno);
  {$ENDIF}
end;

Now, when I run this method on Windows it pops up a message box with 'This is .NET Framework. Horay!!!' I kind of expected that being that it was running on Windows. When I ran it on Linux under Mono, it popped up a message box with the same message, "This is .NET FrameWork. Horay!!!" I was expecting to see Linux message, which is "This is Linux. Horay!!!" If this code is working correctly, then how do you check to see which platform your program is running on in the event you do need to execute different methods only supported by Linux or Mac or windows.

¿Fue útil?

Solución

The compiler directives are evaluated at compile time (hence compiler directives). So the resulting .exe will always state the platform it was compiled on, not the one it is running on. Also, the Delphi-Compiler directives are not defined in this way for Prism / Oxygene language.

The way to retrieve the OS you're running on is a bit tricky (there are for example multiple values stating you're on UNIX), but not overly complicated.

The first place to go is System.Environment.OSVersion.Platform. This enum defines the following values in .NET 2.0: Win32S, Win32Windows, Win32NT, WinCE, Unix, Xbox, MacOSX. MacOS has its own value while Linux and other Unixoid systems share the Unix value.

Mono also defines other values too (see the Mono FAQ entry on determining the platform).

Edit: One possible way would be:

var os: string := if Environment.OSVersion.Platform = System.PlatformID.Unix then
   'Linux/Unix'
else if Environment.OSVersion.Platform = System.PlatformID.MacOSX then
   'Mac OS X'
else
   'Windows';
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top