Programing

양식이로드 된 후 코드를 어떻게 실행합니까?

lottogame 2020. 7. 17. 08:10
반응형

양식이로드 된 후 코드를 어떻게 실행합니까?


.NET에서 Windows Forms에는 Form이로드되기 전에 시작되는 이벤트 (Form.Load)가 있지만 양식이로드 된 후에 시작되는 해당 이벤트가 없습니다. 양식이로드 된 후 일부 논리를 실행하고 싶습니다.

누구든지 솔루션에 대해 조언 할 수 있습니까?


"표시된"이벤트를 사용할 수 있습니다 : MSDN-Form.Shown

"표시된 이벤트는 양식이 처음 표시 될 때만 발생하며, 이후 최소화, 최대화, 복원, 숨기기, 표시 또는 무효화 및 다시 그리기는이 이벤트를 발생시키지 않습니다."


나는 때때로 (로드에서)

this.BeginInvoke((MethodInvoker) delegate {
  // some code
});

또는

this.BeginInvoke((MethodInvoker) this.SomeMethod);

"this"이외의 인스턴스에서 이벤트를 처리하는 경우 "this"를 양식 변수로 변경하십시오.

이렇게하면 호출이 windows-forms 루프로 푸시되므로 양식이 메시지 큐를 처리 할 때 처리됩니다.

[요청에 따라 업데이트]

Control.Invoke / Control.BeginInvoke 메소드는 스레딩에 사용하기위한 것이며 UI 스레드로 작업을 푸시하는 메커니즘입니다. 일반적으로 이것은 작업자 스레드 등에서 사용됩니다. Control.Invoke는 동기 호출을 수행하며, Control.BeginInvoke는 비동기 호출을 수행합니다.

일반적으로 다음과 같이 사용됩니다.

SomeCodeOrEventHandlerOnAWorkerThread()
{
  // this code running on a worker thread...
  string newText = ExpensiveMethod(); // perhaps a DB/web call

  // now ask the UI thread to update itself
  this.Invoke((MethodInvoker) delegate {
      // this code runs on the UI thread!
      this.Text = newText;
  });
}

Windows 메시지 대기열로 메시지를 푸시하여이를 수행합니다. UI 스레드 (어느 시점에서)는 메시지를 대기열에서 꺼내고 대리인을 처리하며 작업자에게 완료되었음을 알립니다.

확인; UI 스레드에서 Control.Invoke / Control.BeginInvoke를 사용하면 어떻게됩니까? 그것은 대처합니다 ... Control.Invoke를 호출하면 메시지 대기열을 차단하면 즉각적인 교착 상태가 발생할 수 있음을 알 수 있습니다. 이미 UI 스레드에 있으면 코드를 즉시 실행합니다 ... 우리를 도와주지 않습니다 ...

그러나 Control.BeginInvoke는 다르게 작동합니다. 이미 UI 스레드에 있더라도 항상 대기열로 작업을 푸시합니다. 이것은 실제로 "순간에"라고 말하는 간단한 방법을 만들지 만 타이머 등의 불편 함이 없습니다 (아직도 같은 일을해야합니다!).


"AfterLoading"을 처음 시작하지 않으면
NEXT Load를 시작하기 위해 등록합니다.

private void Main_Load(object sender, System.EventArgs e)
{
    //Register it to Start in Load 
    //Starting from the Next time.
    this.Activated += AfterLoading;
}

private void AfterLoading(object sender, EventArgs e)
{
    this.Activated -= AfterLoading;
    //Write your code here.
}

나는 같은 문제가 있었고 다음과 같이 해결했다.

실제로 메시지를 표시하고 2 초 후에 자동으로 닫고 싶습니다. 이를 위해 (동적으로) 간단한 양식과 메시지를 표시하는 하나의 레이블을 생성해야 했으므로 1500ms 동안 메시지를 중지하여 사용자가 읽습니다. 그리고 동적으로 생성 된 양식을 닫습니다. 표시된 이벤트 발생 후로드 이벤트. 그래서 코드는

Form MessageForm = new Form();
MessageForm.Shown += (s, e1) => { 
    Thread t = new Thread(() => Thread.Sleep(1500)); 
    t.Start(); 
    t.Join(); 
    MessageForm.Close(); 
};

원하는 경우 양식이 활성화 될 때와 같이 양식의 Activated 이벤트에 코드를 입력 할 수도 있습니다. 첫 번째 활성화에서만 실행되어야한다면 부울 "실행 됨"검사를 넣어야합니다.


이것은 오래된 질문이며 루틴을 시작해야 할 때 더 달려 있습니다. 아무도 null 참조 예외를 원하지 않으므로 항상 null을 먼저 확인한 다음 필요에 따라 사용하는 것이 가장 좋습니다. 그것만으로도 많은 슬픔을 구할 수 있습니다.

The most common reason for this type of question is when a container or custom control type attempts to access properties initialized outside of a custom class where those properties have not yet been initialized thus potentially causing null values to populate and can even cause a null reference exceptions on object types. It means your class is running before it is fully initialized - before you have finished setting your properties etc. Another possible reason for this type of question is when to perform custom graphics.

To best answer the question about when to start executing code following the form load event is to monitor the WM_Paint message or hook directly in to the paint event itself. Why? The paint event only fires when all modules have fully loaded with respect to your form load event. Note: This.visible == true is not always true when it is set true so it is not used at all for this purpose except to hide a form.

The following is a complete example of how to start executing you code following the form load event. It is recommended that you do not unnecessarily tie up the paint message loop so we'll create an event that will start executing your code outside that loop.

using System.Windows.Forms;

namespace MyProgramStartingPlaceExample {

/// <summary>
/// Main UI form object
/// </summary>
public class Form1 : Form
{

    /// <summary>
    /// Main form load event handler
    /// </summary>
    public Form1()
    {
        // Initialize ONLY. Setup your controls and form parameters here. Custom controls should wait for "FormReady" before starting up too.
        this.Text = "My Program title before form loaded";
        // Size need to see text. lol
        this.Width = 420;

        // Setup the sub or fucntion that will handle your "start up" routine
        this.StartUpEvent += StartUPRoutine;

        // Optional: Custom control simulation startup sequence:
        // Define your class or control in variable. ie. var MyControlClass new CustomControl;
        // Setup your parameters only. ie. CustomControl.size = new size(420, 966); Do not validate during initialization wait until "FormReady" is set to avoid possible null values etc. 
        // Inside your control or class have a property and assign it as bool FormReady - do not validate anything until it is true and you'll be good! 
    }

    /// <summary>
    /// The main entry point for the application which sets security permissions when set.
    /// </summary>
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }


    #region "WM_Paint event hooking with StartUpEvent"            
    //
    // Create a delegate for our "StartUpEvent"
    public delegate void StartUpHandler();
    //
    // Create our event handle "StartUpEvent"
    public event StartUpHandler StartUpEvent;
    //
    // Our FormReady will only be set once just he way we intendded
    // Since it is a global variable we can poll it else where as well to determine if we should begin code execution !!
    bool FormReady;
    //
    // The WM_Paint message handler: Used mostly to paint nice things to controls and screen
    protected override void OnPaint(PaintEventArgs e)
    {
        // Check if Form is ready for our code ?
        if (FormReady == false) // Place a break point here to see the initialized version of the title on the form window
        {
            // We only want this to occur once for our purpose here.
            FormReady = true;
            //
            // Fire the start up event which then will call our "StartUPRoutine" below.
            StartUpEvent();
        }
        //
        // Always call base methods unless overriding the entire fucntion
        base.OnPaint(e);
    }
    #endregion


    #region "Your StartUp event Entry point"
    //
    // Begin executuing your code here to validate properties etc. and to run your program. Enjoy!
    // Entry point is just following the very first WM_Paint message - an ideal starting place following form load
    void StartUPRoutine()
    {
        // Replace the initialized text with the following
        this.Text = "Your Code has executed after the form's load event";
        //
        // Anyway this is the momment when the form is fully loaded and ready to go - you can also use these methods for your classes to synchronize excecution using easy modifications yet here is a good starting point. 
        // Option: Set FormReady to your controls manulaly ie. CustomControl.FormReady = true; or subscribe to the StartUpEvent event inside your class and use that as your entry point for validating and unleashing its code.
        //
        // Many options: The rest is up to you!
    }
    #endregion

}

}


You can close your form after some execution..

//YourForm.ActiveForm.Close();

    LoadingForm.ActiveForm.Close();

참고URL : https://stackoverflow.com/questions/218732/how-do-i-execute-code-after-a-form-has-loaded

반응형