developer tip

시작시 단일 양식 숨기기

optionbox 2020. 10. 25. 12:07
반응형

시작시 단일 양식 숨기기


양식이 하나있는 응용 프로그램이 있고 Load 메서드에서 양식을 숨겨야합니다.

양식은 필요할 때 자체적으로 표시되지만 (Outlook 2003 스타일 팝업의 줄을 따라 생각해보십시오),로드시 양식을 지저분하게 숨기는 방법을 알아낼 수 있습니다.

어떤 제안?


C #에서 왔지만 vb.net에서 매우 유사해야합니다.

주 프로그램 파일의 Main 메서드에는 다음과 같은 내용이 있습니다.

Application.Run(new MainForm());

이렇게하면 새 기본 양식이 만들어지고 응용 프로그램의 수명이 기본 양식의 수명으로 제한됩니다.

그러나 Application.Run ()에 대한 매개 변수를 제거하면 양식이 표시되지 않고 애플리케이션이 시작되며 원하는만큼 양식을 표시하거나 숨길 수 있습니다.

Load 메서드에서 양식을 숨기는 대신 Application.Run ()을 호출하기 전에 양식을 초기화합니다. 작업 표시 줄에 아이콘을 표시하기 위해 양식에 NotifyIcon이 있다고 가정합니다. 양식 자체가 아직 표시되지 않은 경우에도 표시 될 수 있습니다. NotifyIcon 이벤트의 핸들러를 호출 Form.Show()하거나 호출 Form.Hide()하면 양식이 각각 표시되고 숨겨집니다.


일반적으로 나중에 양식을 표시하기 위해 트레이 아이콘이나 다른 방법을 사용할 때만이 작업을 수행하지만 기본 양식을 표시하지 않더라도 잘 작동합니다.

기본값이 false 인 Form 클래스에 bool을 만듭니다.

private bool allowshowdisplay = false;

그런 다음 SetVisibleCore 메서드를 재정의합니다.

protected override void SetVisibleCore(bool value)
{            
    base.SetVisibleCore(allowshowdisplay ? value : allowshowdisplay);
}

Application.Run ()은 양식을로드 한 후 .Visible = true로 설정하기 때문에이를 가로 채고 false로 설정합니다. 위의 경우 allowhowdisplay를 true로 설정하여 활성화 할 때까지 항상 false로 설정됩니다.

이제 시작시 양식이 표시되지 않도록하므로 이제 allowhowdisplay = true를 설정하여 올바르게 작동하도록 SetVisibleCore를 다시 활성화해야합니다. 양식을 표시하는 모든 사용자 인터페이스 기능에서이 작업을 수행 할 수 있습니다. 내 예에서는 내 notiyicon 객체의 왼쪽 클릭 이벤트입니다.

private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        this.allowshowdisplay = true;
        this.Visible = !this.Visible;                
    }
}

나는 이것을 사용한다 :

private void MainForm_Load(object sender, EventArgs e)
{
    if (Settings.Instance.HideAtStartup)
    {
        BeginInvoke(new MethodInvoker(delegate
        {
            Hide();
        }));
    }
}

분명히 당신은 당신의 조건으로 if 조건을 변경해야합니다.


    protected override void OnLoad(EventArgs e)
    {
        Visible = false; // Hide form window.
        ShowInTaskbar = false; // Remove from taskbar.
        Opacity = 0;

        base.OnLoad(e);
    }

양식 생성시 (목표에 따라 디자이너, 프로그램 메인 또는 양식 생성자),

 this.WindowState = FormWindowState.Minimized;
 this.ShowInTaskbar = false;

NotifyIcon의 이벤트에서 양식을 표시해야하는 경우 필요에 따라 뒤집습니다.

 if (!this.ShowInTaskbar)
    this.ShowInTaskbar = true;

 if (this.WindowState == FormWindowState.Minimized)
    this.WindowState = FormWindowState.Normal;

연속적인 표시 / 숨기기 이벤트는 Form의 Visible 속성 또는 Show / Hide 메서드를보다 간단하게 사용할 수 있습니다.


작업 표시 줄에서도 앱을 숨기십시오.

그렇게하려면이 코드를 사용하십시오.

  protected override void OnLoad(EventArgs e)
  {
   Visible = false; // Hide form window.
   ShowInTaskbar = false; // Remove from taskbar.
   Opacity = 0;

   base.OnLoad(e);
   }

감사. 루훌


다음으로 기본 양식을 확장하십시오.

using System.Windows.Forms;

namespace HideWindows
{
    public class HideForm : Form
    {
        public HideForm()
        {
            Opacity = 0;
            ShowInTaskbar = false;
        }

        public new void Show()
        {
            Opacity = 100;
            ShowInTaskbar = true;

            Show(this);
        }
    }
}

예를 들면 :

namespace HideWindows
{
    public partial class Form1 : HideForm
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}

이 기사의 추가 정보 (스페인어) :

http://codelogik.net/2008/12/30/primer-form-oculto/


나는이 문제로 많은 어려움을 겪었으며 해결책은 나보다 훨씬 간단합니다. 먼저 여기에서 모든 제안을 시도했지만 결과에 만족하지 못하고 조금 더 조사했습니다. 다음을 추가하면 발견했습니다.

 this.visible=false;
 /* to the InitializeComponent() code just before the */
 this.Load += new System.EventHandler(this.DebugOnOff_Load);

잘 작동합니다. 그러나 나는 더 간단한 해결책을 원했고 다음을 추가하면 밝혀졌습니다.

this.visible=false;
/* to the start of the load event, you get a
simple perfect working solution :) */ 
private void
DebugOnOff_Load(object sender, EventArgs e)
{
this.Visible = false;
}

창 상태를 최소화로 설정하고 작업 표시 줄에 표시를 false로 설정하려고합니다. 그런 다음 양식의 끝에서로드 세트 창 상태를 최대화하고 작업 표시 줄에 true로 표시합니다.

    public frmMain()
    {
        Program.MainForm = this;
        InitializeComponent();

        this.WindowState = FormWindowState.Minimized;
        this.ShowInTaskbar = false;
    }

private void frmMain_Load(object sender, EventArgs e)
    {
        //Do heavy things here

        //At the end do this
        this.WindowState = FormWindowState.Maximized;
        this.ShowInTaskbar = true;
    }

이것을 Program.cs에 넣으십시오.

FormName FormName = new FormName ();

FormName.ShowInTaskbar = false;
FormName.Opacity = 0;
FormName.Show();
FormName.Hide();

양식을 표시하려면 다음을 사용하십시오.

var principalForm = Application.OpenForms.OfType<FormName>().Single();
principalForm.ShowInTaskbar = true;
principalForm.Opacity = 100;
principalForm.Show();

양식에서 OnVisibleChanged 재정의

protected override void OnVisibleChanged(EventArgs e)
{
    this.Visible = false;

    base.OnVisibleChanged(e);
}

특정 시점에 표시해야 할 경우 트리거를 추가 할 수 있습니다.

public partial class MainForm : Form
{
public bool hideForm = true;
...
public MainForm (bool hideForm)
    {
        this.hideForm = hideForm;
        InitializeComponent();
    }
...
protected override void OnVisibleChanged(EventArgs e)
    {
        if (this.hideForm)
            this.Visible = false;

        base.OnVisibleChanged(e);
    }
...
}

다음은 간단한 접근 방식입니다.
C #에 있습니다 (현재 VB 컴파일러가 없습니다).

public Form1()
{
    InitializeComponent();
    Hide(); // Also Visible = false can be used
}

private void Form1_Load(object sender, EventArgs e)
{
    Thread.Sleep(10000);
    Show(); // Or visible = true;
}

양식없이 앱을 시작하면 애플리케이션 시작 / 종료를 직접 관리해야합니다.

보이지 않는 상태에서 양식을 시작하는 것이 더 나은 옵션입니다.


이 예제는 시스템 트레이의 NotifyIcon뿐 아니라 전체 숨김 기능 만 지원하며 클릭 수는 없습니다.

추가 정보 : http://code.msdn.microsoft.com/TheNotifyIconExample


As a complement to Groky's response (which is actually the best response by far in my perspective) we could also mention the ApplicationContext class, which allows also (as it's shown in the article's sample) the ability to open two (or even more) Forms on application startup, and control the application lifetime with all of them.


static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    MainUIForm mainUiForm = new MainUIForm();
    mainUiForm.Visible = false;
    Application.Run();
}

This works perfectly for me:

[STAThread]
    static void Main()
    {
        try
        {
            frmBase frm = new frmBase();               
            Application.Run();
        }

When I launch the project, everything was hidden including in the taskbar unless I need to show it..


I had an issue similar to the poster's where the code to hide the form in the form_Load event was firing before the form was completely done loading, making the Hide() method fail (not crashing, just wasn't working as expected).

The other answers are great and work but I've found that in general, the form_Load event often has such issues and what you want to put in there can easily go in the constructor or the form_Shown event.

Anyways, when I moved that same code that checks some things then hides the form when its not needed (a login form when single sign on fails), its worked as expected.


    static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form1 form1 = new Form1();
            form1.Visible = false;
            Application.Run();

        }
 private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }

In the designer, set the form's Visible property to false. Then avoid calling Show() until you need it.

A better paradigm is to not create an instance of the form until you need it.


Why do it like that at all?

Why not just start like a console app and show the form when necessary? There's nothing but a few references separating a console app from a forms app.

No need in being greedy and taking the memory needed for the form when you may not even need it.


Based on various suggestions, all I had to do was this:

To hide the form:

Me.Opacity = 0
Me.ShowInTaskbar = false

To show the form:

Me.Opacity = 100
Me.ShowInTaskbar = true

I do it like this - from my point of view the easiest way:

set the form's 'StartPosition' to 'Manual', and add this to the form's designer:

Private Sub InitializeComponent()
.
.
.
Me.Location=New Point(-2000,-2000)
.
.
.
End Sub

Make sure that the location is set to something beyond or below the screen's dimensions. Later, when you want to show the form, set the Location to something within the screen's dimensions.

참고URL : https://stackoverflow.com/questions/70272/single-form-hide-on-startup

반응형