프로그램(C# etc.)

프로그램 시작되면서 트레이 아이콘으로 시작하는 코드

질문폭격 2023. 1. 16. 14:49

다음은 통지를 작성하는 방법의 예입니다프로그램이 시작될 때 알림 영역에 표시되는 아이콘:

using System;
using System.Windows.Forms;

class MyForm : Form
{
    NotifyIcon notifyIcon1 = new NotifyIcon();

    public MyForm()
    {
        // Set the icon to display in the notification area
        notifyIcon1.Icon = new Icon("myicon.ico");

        // Set the text to display in the tooltip
        notifyIcon1.Text = "My Program";

        // Make the icon visible
        notifyIcon1.Visible = true;

        // Add a context menu to the icon
        notifyIcon1.ContextMenuStrip = new ContextMenuStrip();
        notifyIcon1.ContextMenuStrip.Items.Add("Exit");
        notifyIcon1.ContextMenuStrip.ItemClicked += new ToolStripItemClickedEventHandler(ContextMenuStrip_ItemClicked);

        // Minimize the form to the notification area when it is loaded
        this.WindowState = FormWindowState.Minimized;
        this.ShowInTaskbar = false;
    }

    private void ContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {
        if (e.ClickedItem.Text == "Exit")
        {
            // Exit the program when the "Exit" menu item is clicked
            Application.Exit();
        }
    }
}

이 예에서는 알림의 새 인스턴스아이콘 클래스는 MyForm 클래스의 생성자에 생성됩니다. 알림 영역에 표시할 아이콘은 Icon 속성을 사용하여 설정하고, 도구 설명에 표시할 텍스트는 Text 속성을 사용하여 설정합니다.

Visible 속성은 true로 설정되어 알림 영역에 아이콘을 표시합니다. 컨텍스트 메뉴는 ContextMenuStrip 클래스의 새 인스턴스를 만들고 Notify의 ContextMenuStrip 속성에 할당하여 아이콘에 추가됩니다아이콘 개체입니다. 상황에 맞는 메뉴에는 "종료" 항목이 있으며 사용자가 이 항목을 클릭하면 응용프로그램이 종료됩니다.

WindowState 속성을 FormWindowState로 설정하여 로드 시 알림 영역으로 폼이 최소화됩니다.최소화되고 ShowInTaskbar 속성이 false입니다. 이렇게 하면 양식은 작업 표시줄에 표시되지 않지만 아이콘은 알림 영역에 표시됩니다.

아이콘 작업을 마치면 알림을 삭제해야 합니다아이콘 개체가 사용하는 리소스를 해제합니다.
양식 닫기 이벤트 또는 상황에 맞는 메뉴의 종료 이벤트에서 이 작업을 수행할 수 있습니다.