How to deterimine whether .Net DLL is used in a GU

2019-07-07 05:01发布

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条回答
在下西门庆
2楼-- · 2019-07-07 05:26

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.

查看更多
Rolldiameter
3楼-- · 2019-07-07 05:27

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.

查看更多
萌系小妹纸
4楼-- · 2019-07-07 05:31

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

查看更多
再贱就再见
5楼-- · 2019-07-07 05:39

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.

查看更多
登录 后发表回答