views:

154

answers:

3

Hi, i want to write a C# lib, or a reference service, so that if a application reference my lib, and when the application runs, the function in my function can be run without any invoked?

for example, i got a lib, keep reading the memory usage of the platform, when the memory was up to 80%, i pop up a message to the user, it is time to close the application.

so..when i create a another application, and want my new application has the mem check feature, i just need to reference it then after my new application run, the mem check will be fired together..

so..how can i do these?

+2  A: 

Create a static constructor for your class - this constructor will be run once, and only once, the first time the host application references anything related to your class.

You could create a thread to run some background checking process, hook into an event of the Application object, or whatever you need.

Note however, that you'll need to do more than just add a project reference to your assembly - an assembly is only loaded into an App Domain when something in that assembly is referenced by existing code.

Bevan
hmm.....what i can do is that, even nothing is referenced by the existing code, my assembly just add as a reference, can the static constructor still work?...i don`t think it will work..anyway,, i will try it out later..thanks..
shrimpy
If your code never uses anything from the assembly, it will never be loaded into the App domain. The CLR doesn't automatically load every referenced assembly at startup, it only loads assemblies that are needed, as they are needed.
Bevan
A: 

The term you're looking for is "Win32 application hook." There's a decent introduction to managed hook injection here: http://msdn.microsoft.com/en-us/magazine/cc188966.aspx

I'm not sure you can monitor system memory consumption with an application hook, though. And unfortunately, you cannot write a global hook in managed code because global hooks require a well-defined entry point (a DLL export). This is really something best suited for C++.

Richard Berg
A: 

It is possible to create traditional DLL exports in an assembly (via ILASM or the now defunct Delphi.NET) but not really recommended. (search for reverse p/invoke)

Another approach is to create a C++/CLI intermediate dll to call your managed code. But to be perfectly honest, I reckon you are simply better off just creating a native DLL with C++ or Delphi.

Edit:

Ok, firstly a disclaimer, I work for Quest Software (the company that makes this tool that I am about to plug). That said...

OS Monitoring is actually not as straight forward as you might think, things like memory consumption, process monitoring etc is...well, pernickety. You may find that somthing like Spotlight on Windows (Freeware for first 10 licences) would suit your purpose ?

Tim Jarvis
hmm....can i do in C#???? actually the application is running on server, my task is to monitor the server at run time, ....hmm....
shrimpy