Check memory usage (win32)

Hi

I'm looking for some Windows API functions which will tell me the current memory usage as viewed in the Performance tab of Task manager. Such as "Physical Memory" "Kernel memory"

Thanks

-mike
nerdmikeAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jhanceCommented:
These are all available via WMI (Windows Management Instrumentation).  Example:

http://www.computerperformance.co.uk/Logon/LogonScript_Memory.htm
0
nerdmikeAuthor Commented:
I'm looking for API functions not some script
0
jhanceCommented:
The API is called WMI (as I said already!).

The script demonstrates the use of WMI.  It's available from any programming language including scripts.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

nerdmikeAuthor Commented:
I don't see anything there that can help me

If you would be so kind to write a program in C which will print the total kernel memory (as shown on Task Manager->Peformance) on stdout, it will be helpful enough.
0
kblack05Commented:
What's wrong with the mem command?

C:\WINDOWS\system32>mem


    655360 bytes total conventional memory
    655360 bytes available to MS-DOS
    633952 largest executable program size

   1048576 bytes total contiguous extended memory
         0 bytes available contiguous extended memory
    941056 bytes available XMS memory
           MS-DOS resident in High Memory Area

C:\WINDOWS\system32>mem /?
Displays the amount of used and free memory in your system.

MEM [/PROGRAM | /DEBUG | /CLASSIFY]

  /PROGRAM or /P   Displays status of programs currently loaded in memory.
  /DEBUG or /D     Displays status of programs, internal drivers, and other
                   information.
  /CLASSIFY or /C  Classifies programs by memory usage. Lists the size of
                   programs, provides a summary of memory in use, and lists
                   largest memory block available.

C:\WINDOWS\system32>
0
nerdmikeAuthor Commented:
mem is not a win32 api function
0
jhanceCommented:
Here is a C++ souce code that does the same thing as the script I posted.  All WMI objects are access via the same mechanism.  I'm not at all sure exactly what WMI parameter is the one you are referring to in your question but I'm sure it's available via this interface since WMI is what the Task Manager uses to get its information.

The Microsoft Script-O-Matic, while script oriented, is an invaluable resource to use to explore the WMI namespace.  You might want to download it and check it out.


#ifndef _WIN32_DCOM
#define _WIN32_DCOM
#endif

#include <windows.h>
#include <objbase.h>
#include <atlbase.h>
#include <iostream>
#include <wbemidl.h>
#include <comutil.h>


int main( int argc, char** argv )
{
      HRESULT hr = CoInitializeEx( NULL, COINIT_MULTITHREADED );
      if ( FAILED( hr ) )
      {
            std::cerr << "COM initialization failed" << std::endl;
            return -1;
      }

      // setup process-wide security context
      hr = CoInitializeSecurity( NULL, // we're not a server
                                             -1, // we're not a server
                                             NULL, // dito
                                             NULL, // reserved
                                             RPC_C_AUTHN_LEVEL_DEFAULT, // let DCOM decide
                                             RPC_C_IMP_LEVEL_IMPERSONATE,
                                             NULL,
                                             EOAC_NONE,
                                             NULL );
      if ( FAILED( hr ) )
      {
            std::cerr << "Security initialization failed" << std::endl;
            return -1;
      }

      int result = 0;
      // we're going to use CComPtr<>s, whose lifetime must end BEFORE CoUnitialize is called
      {
            // connect to WMI
            CComPtr< IWbemLocator > locator;
            hr = CoCreateInstance( CLSID_WbemAdministrativeLocator, NULL,
                                          CLSCTX_INPROC_SERVER,
                                          IID_IWbemLocator, reinterpret_cast< void** >( &locator ) );
            if ( FAILED( hr ) )
            {
                  std::cerr << "Instantiation of IWbemLocator failed" << std::endl;
                  return -1;
            }

            // connect to local service with current credentials
            CComPtr< IWbemServices > service;
            hr = locator->ConnectServer( L"root\\cimv2", NULL, NULL, NULL,
                                                       WBEM_FLAG_CONNECT_USE_MAX_WAIT,
                                                       NULL, NULL, &service );
            if ( SUCCEEDED( hr ) )
            {
                  // execute a query
                  CComPtr< IEnumWbemClassObject > enumerator;

                  hr = service->ExecQuery( L"WQL", L"SELECT TotalPhysicalMemory FROM Win32_LogicalMemoryConfiguration",
                                                     WBEM_FLAG_FORWARD_ONLY, NULL, &enumerator );
                  if ( SUCCEEDED( hr ) )
                  {
                        // read the first instance from the enumeration (only one on single processor machines)
                        CComPtr< IWbemClassObject > TotalPhysicalMemory = NULL;
                        ULONG retcnt;
                        hr = enumerator->Next( WBEM_INFINITE, 1L, reinterpret_cast<IWbemClassObject**>( &TotalPhysicalMemory ), &retcnt );
                        if ( SUCCEEDED( hr ) )
                        {
                              if ( retcnt > 0 )
                              {
                                    // we have a processor installed :)
                                    // now extract a property value
                                    _variant_t var_val;
                                    hr = TotalPhysicalMemory->Get( L"TotalPhysicalMemory", 0, &var_val, NULL, NULL );
                                    if ( SUCCEEDED( hr ) )
                                    {
                                          _bstr_t str = var_val;
                                          std::cout << "TotalPhysicalMemory: " << str << std::endl;
                                    }
                                    else
                                    {
                                          std::cerr << "IWbemClassObject::Get failed" << std::endl;
                                          result = -1;
                                    }
                              }
                              else
                              {
                                    std::cout << "Enumeration empty" << std::endl;
                              }
                        }
                        else
                        {
                              std::cerr << "Error in iterating through enumeration" << std::cerr;
                              result = -1;
                        }
                  }
                  else
                  {
                        std::cerr << "Query failed" << std::endl;
                        result = -1;
                  }
            }
            else
            {
                  std::cerr << "Couldn't connect to service" << std::endl;
                  result = -1;
            }
      }
      CoUninitialize();

      return result;
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jhanceCommented:
Oh, and one more time.  There is _NO_ WIN32 API function that returns what you are asking about.  You must use one of the methods that Microsoft has provided for that purpose.  So regardless of how many times you ask the same question, the answer will still be the same.  WMI is the way Microsoft intends you to get this information and, in fact, is the way they do it themselves.
0
callrsCommented:
I'm wondering the same thing. But I'd ask for more..like how to get the memory usage of EACH APPLICATION, and each PROCESS, not just total memory usage. :) .. And how to do so not just in XP, but in Win98
0
Bone99Commented:
Try this url:
http://www.codeproject.com/Purgatory/MemoryTracker.asp

I think the article will show you what you want to know.
0
MilanKMCommented:
Here is a VB6 through which you can easily track the memory status. Just take a Timer control (Set Interval=1, Enabled=True) & 7 labels. Then just copy & paste the following code.

Private Declare Sub GlobalMemoryStatus Lib "kernel32" (lpBuffer As MEMORYSTATUS)
Private Type MEMORYSTATUS
        dwLength As Long
        dwMemoryLoad As Long
        dwTotalPhys As Long
        dwAvailPhys As Long
        dwTotalPageFile As Long
        dwAvailPageFile As Long
        dwTotalVirtual As Long
        dwAvailVirtual As Long
End Type

Private Sub Form_Load()
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Timer()
Dim memStat As MEMORYSTATUS
    memStat.dwLength = Len(memStat)
    Call GlobalMemoryStatus(memStat)
    Label1.Caption = Format(memStat.dwMemoryLoad, "###,###,###")
    Label2.Caption = Format(memStat.dwTotalPhys, "###,###,###")
    Label3.Caption = Format(memStat.dwAvailPhys, "###,###,###")
    Label4.Caption = Format(memStat.dwTotalPageFile, "###,###,###")
    Label5.Caption = Format(memStat.dwAvailPageFile, "###,###,###")
    Label6.Caption = Format(memStat.dwTotalVirtual, "###,###,###")
    Label7.Caption = Format(memStat.dwAvailVirtual, "###,###,###")
    Label8.Caption = Format(memStat.dwTotalVirtual - memStat.dwAvailVirtual, "###,###,###")
End Sub

Thanks
MilanKM
0
MilanKMCommented:
By the way GlobalMemoryStatus is a Win32 API under Kernal32 which is called in the program.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.