views:

222

answers:

4

How do I determine in a .Net DLL whether it's running in a Windows GUI application or web service? I've got a low level class which is being shared between two applications and need to disable message boxes when it's used in a web service.

The Windows application has over 200 solutions and I'm not in a position to re-factor the existing code. The web service needs to reuse some functionality and I'm looking for a quick fix.

+4  A: 

If it is running in a web context, HttpContext.Current will not be null.

leppie
That what I did for some apps, and it worked fine.
controlbreak
+3  A: 

Just a piece of general advice, your low level class should probably not be using the message boxes itself, but should allow an intermediate (closer to the interface) class to handle cases where you might want a messagebox.

If you did this, then you'd simply use different higher-level classes for the web than for the desktop, and each would have notification facilities appropriate to its context.

Adam Bellaire
This is the answer. Refactor out all messagebox usage in your library classes.It is the responsibility of callers to interpret results and inform users.
Will
WTF, this is NOT the answer to the question asked.
leppie
Don't shoot the messenger! As I said in my answer, this is general advice, and was not intended to be an answer to his question as asked.
Adam Bellaire
A: 

I don't know if this will work, but it might. Use these Win32 calls:

GetModuleFileNameEx to get the dll's exe and save it for later comparison.
EnumWindows to get all top level windows.
GetWindowModuleFileName to translate the window handles from EnumWindows to module names.

If you can find your own exe among the results of GetWindowModuleFileName, then your dll is running in a GUI app.

Corey Trager
+2  A: 

You could use the Environment.UserInteractive property.

The UserInteractive property reports false for a Windows process or a service like IIS that runs without a user interface. If this property is false, do not display modal dialogs or message boxes because there is no graphical user interface for the user to interact with.

I know you are unable to do this, but.... You also might want to think about your application design.

GvS
Nice tip, thanks :)
leppie
Note however, that this Environment.UserInteractive will be true for any application that is "associated with a display". This also includes console applications (which can also display message boxes of course - but you might not want that).
Christian.K
Also HttpContext.Current, will be null in this case.
GvS