vb. NET запуск формы с классом vb вместо формы, но форма закрывается, как только она запускается - PullRequest
0 голосов
/ 06 мая 2020

Я хочу использовать объект для запуска моей формы в VB, но когда я использую объект, форма открывается, но сразу после этого закрывается. Я использую класс vb в качестве объекта для запуска приложения в свойствах моих проектов. Проблема, с которой я сталкиваюсь, заключается в том, что как только он показывает форму, все закрывается. Ничего не остается открытым. Как я могу это исправить? Вот мой код для объекта и форм:

AppStarter.vb:

Public Class AppStarter
    Shared Sub Main()
        If System.IO.File.Exists("C:\Mingw\bin\g++.exe") Then
            Form1.Show()
        Else
            ErrorPage.Show()
            MsgBox("Test")
        End If
    End Sub
End Class

Form1:

Public Class Form1
    Dim fd As OpenFileDialog = New OpenFileDialog()
    Dim fld As FolderBrowserDialog = New FolderBrowserDialog()
    Dim strFileName As String
    Dim strCompiledFileName As String
    Dim strFileDestination As String
    Dim strFilePath As String
    Dim test As Boolean

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Sub cmdCompile_Click(sender As Object, e As EventArgs) Handles cmdCompile.Click
        If txtCompiledFileName.Text <> "" And strFilePath <> "" And strFileDestination <> "" Then
            strCompiledFileName = txtCompiledFileName.Text
            Try
                Process.Start("cmd", "/c cd " + strFileDestination + " & g++ " + strFilePath + " -o " + strCompiledFileName)
                MsgBox("Compiled Successfully!")
                ClearVar()
            Catch ex As Exception
                MsgBox(ex)
                ClearVar()
            End Try
        Else
            MsgBox("Missing compiled file name or file path.", MessageBoxIcon.Error)
        End If
    End Sub

    Private Sub cmdChooseFile_Click(sender As Object, e As EventArgs) Handles cmdChooseFile.Click
        fd.Title = "Open File Dialog"
        fd.InitialDirectory = "C:\"
        fd.Filter = "C/C++ Files |*.c; *.cpp"
        fd.FilterIndex = 1
        fd.RestoreDirectory = True
        fd.DereferenceLinks = True

        If fd.ShowDialog() = DialogResult.OK Then
            strFileName = System.IO.Path.GetFileName(fd.FileName)
            strFilePath = fd.FileName
        End If

        lblChosenFile.Text = strFileName
    End Sub

    Private Sub cmdFileDestination_Click(sender As Object, e As EventArgs) Handles cmdFileDestination.Click
        fld.Description = "Select a folder to extract to:"
        fld.ShowNewFolderButton = True
        fld.SelectedPath = strFileDestination
        fld.RootFolder = System.Environment.SpecialFolder.MyComputer

        If fld.ShowDialog() = DialogResult.OK Then
            strFileDestination = fld.SelectedPath
            lblChosenFolder.Text = strFileDestination
        End If
    End Sub

    Public Sub ClearVar()
        txtCompiledFileName.Text = ""
        lblChosenFile.Text = "No chosen file"
        lblChosenFolder.Text = ""
    End Sub
End Class

ErrorPage:

Public Class ErrorPage
    Dim webAddress As String = "https://osdn.net/projects/mingw/releases/"

    Private Sub ErrorPage_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Sub cmdYes_Click(sender As Object, e As EventArgs) Handles cmdYes.Click
        Process.Start(webAddress)
    End Sub

    Private Sub cmdNo_Click(sender As Object, e As EventArgs) Handles cmdNo.Click
        Form1.Close()
        Close()
    End Sub


    Private Const CP_NOCLOSE_BUTTON As Integer = &H200
    Protected Overloads Overrides ReadOnly Property CreateParams() As CreateParams
        Get
            Dim myCp As CreateParams = MyBase.CreateParams
            myCp.ClassStyle = myCp.ClassStyle Or CP_NOCLOSE_BUTTON
            Return myCp
        End Get
    End Property
End Class

1 Ответ

1 голос
/ 06 мая 2020

Если вы хотите написать свой собственный метод Main и отобразить свою собственную форму запуска, вам необходимо вызвать Application.Run и передать форму в качестве аргумента. Вызываемый вами метод Show немедленно возвращается, и поэтому ваш метод Main завершается, а приложение закрывается.

Вот как запускаются приложения C# WinForms:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

Вы должен делать в основном то же самое:

Module Program

    <STAThread>
    Sub Main()
        Application.EnableVisualStyles()
        Application.SetCompatibleTextRenderingDefault(False)
        Application.Run(Form1)
    End Sub

End Module

Если вам нужно поместить этот вызов Application.Run внутри блока If, пусть будет так.

Тем не менее, вероятно, нет смысла делая это. Необходимая вам функциональность уже встроена в VB Application Framework. Просто создайте проект приложения VB WinForms как обычно, а форму запуска оставьте выбранной как обычно. Затем вы можете открыть файл кода событий приложения из свойств проекта и обработать событие Startup. В этом обработчике событий, если вы установите e.Cancel на True, приложение завершится без создания формы запуска. Это означает, что вы можете сделать это:

Imports System.IO
Imports Microsoft.VisualBasic.ApplicationServices

Namespace My
    ' The following events are available for MyApplication:
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
    Partial Friend Class MyApplication

        Private Sub MyApplication_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup
            If Not File.Exists("C:\Mingw\bin\g++.exe") Then
                'Display error page and be sure to call ShowDialog rather than Show.

                'Exit without creating the startup form.
                e.Cancel = True
            End If
        End Sub

    End Class
End Namespace

Если файл действительно существует, приложение запустится нормально с отображаемой формой запуска.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...