2012-07-04 4 views
1

Visual Basic을 통해 내 PC에 설치된 실제 메모리 (총 RAM)를 얻으려고합니다. 문제는 "0 바이트"를 반환하는 것입니다. 요 사용률, 여유 RAM, 총 페이징, 무료 페이지 및 Windows 용 RAM의 리소스 모니터와 같은 사용량을 보여주는 그래프의 양을 얻으십시오. 문제는 내가 처음에 사용 가능한 RAM의 정확한 양을 얻을 수 없다는 것입니다. 다른 사람들과 함께 나아 간다.Visual Basic 실제 메모리

내가 뭘 잘못하고있어? 감사합니다. http://s18.postimage.org/7zn5adst3/Memory.jpg 괜찮나 내가 당신을 매우 게 감사 할 수 있습니다 : 나는 이런 식으로 뭔가를 할 수 있다면 궁금하네요이 problem.Now를 해결 한

Option Strict On 
Option Explicit On 
Imports System.Math 
Imports System.Management 
Imports System.Runtime.InteropServices 
Public Class Form1 
    Inherits System.Windows.Forms.Form 
#Region " API " 
    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi)> _ 
    Private Structure MEMORYSTATUSEX 
     Dim dwLength As Integer 
     Dim dwMemoryLoad As Integer 
     Dim ullTotalPhys As ULong 
    End Structure 
    Private memoryInfo As MEMORYSTATUSEX 
    Private Declare Auto Sub GlobalMemoryStatusEx Lib "kernel32" (ByRef lpBuffer As MEMORYSTATUSEX) 
#End Region 


#Region " Variables " 

    Private mullTotalRAM As ULong 

#End Region 

#Region " Form Events " 
    Private Sub Form1_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load 
     ' set title 
     Me.Text = My.Application.Info.Title & " " & My.Application.Info.Version.Major.ToString & "." & _ 
      My.Application.Info.Version.Minor.ToString 

     Application.DoEvents() 
     GetMemoryInfo() 
     Timer1.Enabled = True 
    End Sub 

#End Region 

#Region " Information Gathering and Display " 

    Private Sub GetMemoryInfo() 

     System.Windows.Forms.Application.DoEvents() 

     ' set size of structure (required by this api call) 
     memoryInfo.dwLength = Marshal.SizeOf(memoryInfo) 
     GlobalMemoryStatusEx(memoryInfo) 

     mullTotalRAM = memoryInfo.ullTotalPhys 

     txtRAM.Text = FormatBytes(mullTotalRAM) 

    End Sub 

#End Region 

#Region " Update Timer " 

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) 

     GetMemoryInfo() 

     Application.DoEvents() 

    End Sub 

#End Region 


#Region " Formatting Routines " 

    Private Function FormatBytes(ByVal ullBytes As ULong) As String 
     Dim dblTemp As Double 

     Try 
      Select Case ullBytes 
       Case Is >= 1073741824 'GB 
        dblTemp = CDbl(ullBytes/1073741824) 
        Return FormatNumber(dblTemp, 2) & " GB" 
       Case 1048576 To 1073741823 
        dblTemp = CDbl(ullBytes/1048576) 'MB 
        Return FormatNumber(dblTemp, 0) & " MB" 
       Case 1024 To 1048575 
        dblTemp = CDbl(ullBytes/1024) 'KB 
        Return FormatNumber(dblTemp, 0) & " KB" 
       Case 0 To 1023 
        dblTemp = ullBytes ' bytes 
        Return FormatNumber(dblTemp, 0) & " bytes" 
       Case Else 
        Return "" 
      End Select 
     Catch 
      Return "" 
     End Try 

    End Function 


#End Region 


    Private Sub ramaTotalRAM_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ramaTotalRAM.Enter 

    End Sub 

    Private Sub txtRAM_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtRAM.TextChanged 

    End Sub 
End Class 

:

내 코드입니다 많은.

+0

가 실행중인 어떤 운영 시스템 (.dll는 코드에서 누락되었음을 통지)이에 DECL 당신의 API를 변경 ? –

+0

이것은 VB가 아닌 VB.Net입니다. – Bob77

+0

@ Bob Riemersma : Visual Studio 2008을 사용하고 있으며 .vb 응용 프로그램입니다 ("Form1.vb"는 그 이름 임). –

답변

2

이 작업을 완수하기 위해 Microsoft.VisualBasic.Devices.ComputerInfo 클래스를 볼 수 있습니다 :

TotalPhysicalMemory

MsgBox(String.Format("TotalPhysicalMemory: {0} MBytes", System.Math.Round(My.Computer.Info.TotalPhysicalMemory/(1024 * 1024)), 2).ToString) 
,691 363,210

AvailablePhysicalMemory

MsgBox(String.Format("AvailablePhysicalMemory: {0} MBytes", System.Math.Round(My.Computer.Info.AvailablePhysicalMemory/(1024 * 1024)), 2).ToString) 

TotalVirtualMemory

MsgBox(String.Format("TotalVirtualMemory: {0} MBytes", System.Math.Round(My.Computer.Info.TotalVirtualMemory/(1024 * 1024)), 2).ToString) 

AvailableVirtualMemory

,617,
MsgBox(String.Format("AvailableVirtualMemory: {0} MBytes", System.Math.Round(My.Computer.Info.AvailableVirtualMemory/(1024 * 1024)), 2).ToString) 

또는

Private Declare Auto Sub GlobalMemoryStatusEx Lib "kernel32.dll" (ByRef lpBuffer As MEMORYSTATUSEX) 
+0

API 선언에서 "kernel32.dll"을 변경하여도 여전히 작동하지 않습니다. 위의 코드는 작동합니다. 대단히 감사합니다. 또한 이전 버전을 시도했습니다. 왜 내 방법이 ' T는 작품 이후 내가 charm.I처럼 작동하는 모델로 사용하고있어 내가 마지막 case.If에서 0 바이트를 얻으면 나는 0을 1023으로 그 부분을 삭제한다. 나는 그것을 실행할 때 아무것도 반환하지 않는다. 그 상자는 비어 있습니다. 아직 이해할 수 없습니다. 대단히 감사합니다. –

0

여기 작업 예 pastebin입니다

내가 GlobalMemoryStatusEx의 정의와 아래 MEMORYSTATUSEX

Private Declare Auto Sub GlobalMemoryStatusEx Lib "kernel32" (<[In](), Out()> lpBuffer As MEMORYSTATUSEX) 

을 사용하고

Private memoryInfo As MEMORYSTATUSEX = New MEMORYSTATUSEX 

처럼 선언하여이 작업을 얻을 수 있었다 댓글 작성

'memoryInfo.dwLength = CUInt(Marshal.SizeOf(memoryInfo)) 

MEMORYSTATUSEX에 대한 구조체 정의를 어디서 얻었는지 잘 모르겠지만 Pinvoke.net에 따르면이 구조체는 있어야합니다.

<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _ 
Public Class MEMORYSTATUSEX 

    ''' <summary> 
    ''' Initializes a new instance of the <see cref="T:MEMORYSTATUSEX" /> class. 
    ''' </summary> 
    Public Sub New() 
    Me.dwLength = CType(Marshal.SizeOf(GetType(MEMORYSTATUSEX)), UInt32) 
    End Sub 
    ' Fields 
    ''' <summary> 
    ''' Size of the structure, in bytes. You must set this member before calling GlobalMemoryStatusEx. 
    ''' </summary> 
    Public dwLength As UInt32 
    ''' <summary> 
    ''' Number between 0 and 100 that specifies the approximate percentage of physical memory that is in use (0 indicates no memory use and 100 indicates full memory use). 
    ''' </summary> 
    Public dwMemoryLoad As UInt32 
    ''' <summary> 
    ''' Total size of physical memory, in bytes. 
    ''' </summary> 
    Public ullTotalPhys As UInt64 
    ''' <summary> 
    ''' Size of physical memory available, in bytes. 
    ''' </summary> 
    Public ullAvailPhys As UInt64 
    ''' <summary> 
    ''' Size of the committed memory limit, in bytes. This is physical memory plus the size of the page file, minus a small overhead. 
    ''' </summary> 
    Public ullTotalPageFile As UInt64 
    ''' <summary> 
    ''' Size of available memory to commit, in bytes. The limit is ullTotalPageFile. 
    ''' </summary> 
    Public ullAvailPageFile As UInt64 
    ''' <summary> 
    ''' Total size of the user mode portion of the virtual address space of the calling process, in bytes. 
    ''' </summary> 
    Public ullTotalVirtual As UInt64 
    ''' <summary> 
    ''' Size of unreserved and uncommitted memory in the user mode portion of the virtual address space of the calling process, in bytes. 
    ''' </summary> 
    Public ullAvailVirtual As UInt64 
    ''' <summary> 
    ''' Size of unreserved and uncommitted memory in the extended portion of the virtual address space of the calling process, in bytes. 
    ''' </summary> 
    Public ullAvailExtendedVirtual As UInt64 
End Class 

또한 몇 가지 간단한 하나 라이너

Dim info As Microsoft.VisualBasic.Devices.ComputerInfo = New Microsoft.VisualBasic.Devices.ComputerInfo 
Debug.Print(CStr(info.TotalPhysicalMemory)) 
Debug.Print(CStr(info.TotalVirtualMemory)) 
Debug.Print(CStr(info.AvailablePhysicalMemory)) 
+0

나는 비슷한 응용 프로그램을 가지고 있으며 MEMORYSTATUSEX에 사용되며 작동합니다. RAM 용량이 적당하지만 내 경우에는 작동하지 않습니다. –

+0

나는 그냥 나에게 보여 권리 amount.Is가 output.It를 표시하는 대화 상자에 대한 뭔가 내가 웹에서 발견 가지고 result.In로 무료 RAM 여전히 "0 바이트"유사한 응용 프로그램을 보여주는 부분 완료 읽기 전용으로 설정됩니다. true, accept는 true를 반환하고 modifiers는 public을 반환합니다. –

+0

@TeoRoxy는 몇 가지 추가 정보를 추가했습니다. 구조를 사용하여 코드를 작동시킬 수 없었습니다. 게시 한 코드를 사용하고 심지어 GlobalMemoryStatusEX 선언을 변경해야했습니다. 위의 내용이 작동하므로 왜 당신의 것이 작동하지 않는 것인지 확신 할 수 없습니다. –

0
Friend Sub ReleaseMemory() 
     Try 
      GC.Collect() 
      GC.WaitForPendingFinalizers() 
      If Environment.OSVersion.Platform = PlatformID.Win32NT Then 
       SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1) 
      End If 
     Catch ex As Exception 
      LogError(ex.ToString()) 
     End Try 
    End Sub