c# - .NET 最小化到托盘并最小化所需资源

标签 c# .net vb.net visual-studio winforms

我有一个可以最小化到系统托盘的 WinForms 应用程序(我使用的是 VB)。我使用了多篇文章中描述的“hackish”方法,利用 NotifyIcon 并玩弄 Form_Resize 事件。

这一切在美学上都很好,但使用的资源和内存不受影响。我希望能够在最小化到系统托盘时最小化资源,就像 Visual Studio 一样。如果您在 Visual Studio 中编码,内存使用量可能会上升(取决于项目大小)到 500 MB 以上,但是当将 Visual Studio 最小化到任务栏时,内存会急剧减少到(我假设的)最小量.

有没有人知道如何完成此操作?

这是应用程序的简短描述,如果有人认为它相关的话:我有一个带有 ListView 的窗口窗体,其中包含我的 IT 部门的工单。该应用程序有一个“监听器”,在提交新工作订单时发出通知。因此,当应用程序在系统托盘中运行时,我真正要做的就是每隔几分钟将 ListView 中的项目数与 SQL 表中的行数进行比较。

编辑:更具体地说,Windows 窗体本质上具有通过控件使用的线程和资源,当窗体不可见时(在系统托盘中),这些资源仍在使用中。我能做些什么来最小化这些资源,除了杀死所有控件并在恢复表单时重新绘制它们。

最佳答案

调用 MiniMizeMemory() 将进行垃圾收集,修剪进程的工作大小,然后压缩进程的堆。

public static void MinimizeMemory()
{
    GC.Collect(GC.MaxGeneration);
    GC.WaitForPendingFinalizers();
    SetProcessWorkingSetSize(
        Process.GetCurrentProcess().Handle,
        (UIntPtr)0xFFFFFFFF,
        (UIntPtr)0xFFFFFFFF);

    IntPtr heap = GetProcessHeap();

    if (HeapLock(heap))
    {
        try
        {
            if (HeapCompact(heap, 0) == 0)
            {
                // error condition ignored
            }
        }
        finally
        {
            HeapUnlock(heap);
        }
    }
}

[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetProcessWorkingSetSize(
    IntPtr process,
    UIntPtr minimumWorkingSetSize,
    UIntPtr maximumWorkingSetSize);

[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetProcessHeap();

[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool HeapLock(IntPtr heap);

[DllImport("kernel32.dll")]
internal static extern uint HeapCompact(IntPtr heap, uint flags);

[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool HeapUnlock(IntPtr heap);

关于c# - .NET 最小化到托盘并最小化所需资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/263234/

相关文章:

c# - 设置组合框的下拉高度(winrt)

c# - 如何检测父进程的关闭?

c# - Visual Studio 2015 中的共享项目和类库有什么区别?

c# - 如何动态添加 HTML 元素 (ASP.NET)

asp.net - 我如何查看我的 Visual Basic 项目?

c# - 如何在N层应用中实现IDependencyResolver?

c# - 用C#生成完全随机的偶数

c# - 在 office 2010 中将受密码保护的 OpenXml Word 文档重新保存为受密码保护的二进制 Word 时显示错误

c# - 任务并行库和外部 SQL Server

vb.net - vb中的子串