Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with closing a form, application closes 1

Status
Not open for further replies.

aspvbnetnerd

Programmer
May 16, 2006
278
0
0
SE
I have a form that is called FormLogin and FormLogin is the startup form.

If the user is validated the I want to show the Main form (FormMain) and close then close the FormLogin form.

but when I do me.close the applicationen closes.

Code:
Dim FormMain As New ArkivApp.FormMain
FormMain.Show()
Me.Close()

What am I doing wrong?

George
 
George:

You have to hide the Login form if you are using it as a startup form.

Here is exactly what you're looking for. You will have to instantiate the varibles, but other than that, you should be able to catch on.

Code:
Imports VB = Microsoft.VisualBasic
Imports SO = System.IO
Public Class PW
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents cbUser As System.Windows.Forms.ComboBox
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents txtPWord As System.Windows.Forms.TextBox
    Friend WithEvents btnOK As System.Windows.Forms.Button
    Friend WithEvents btnCancel As System.Windows.Forms.Button
    Friend WithEvents Label2 As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(PW))
        Me.cbUser = New System.Windows.Forms.ComboBox
        Me.Label1 = New System.Windows.Forms.Label
        Me.txtPWord = New System.Windows.Forms.TextBox
        Me.btnOK = New System.Windows.Forms.Button
        Me.btnCancel = New System.Windows.Forms.Button
        Me.Label2 = New System.Windows.Forms.Label
        Me.SuspendLayout()
        '
        'cbUser
        '
        Me.cbUser.Location = New System.Drawing.Point(24, 32)
        Me.cbUser.Name = "cbUser"
        Me.cbUser.Size = New System.Drawing.Size(232, 21)
        Me.cbUser.TabIndex = 0
        '
        'Label1
        '
        Me.Label1.Location = New System.Drawing.Point(24, 16)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(232, 16)
        Me.Label1.TabIndex = 1
        Me.Label1.Text = "&User Name"
        Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'txtPWord
        '
        Me.txtPWord.Location = New System.Drawing.Point(24, 88)
        Me.txtPWord.Name = "txtPWord"
        Me.txtPWord.PasswordChar = Microsoft.VisualBasic.ChrW(42)
        Me.txtPWord.Size = New System.Drawing.Size(224, 20)
        Me.txtPWord.TabIndex = 2
        Me.txtPWord.Text = ""
        '
        'btnOK
        '
        Me.btnOK.Cursor = System.Windows.Forms.Cursors.Hand
        Me.btnOK.FlatStyle = System.Windows.Forms.FlatStyle.Popup
        Me.btnOK.Location = New System.Drawing.Point(24, 136)
        Me.btnOK.Name = "btnOK"
        Me.btnOK.TabIndex = 3
        Me.btnOK.Text = "&OK"
        '
        'btnCancel
        '
        Me.btnCancel.Cursor = System.Windows.Forms.Cursors.Hand
        Me.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.Popup
        Me.btnCancel.Location = New System.Drawing.Point(176, 136)
        Me.btnCancel.Name = "btnCancel"
        Me.btnCancel.TabIndex = 4
        Me.btnCancel.Text = "&Cancel"
        '
        'Label2
        '
        Me.Label2.Location = New System.Drawing.Point(24, 72)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(232, 16)
        Me.Label2.TabIndex = 5
        Me.Label2.Text = "&Password"
        Me.Label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'PW
        '
        Me.AcceptButton = Me.btnOK
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.CancelButton = Me.btnCancel
        Me.ClientSize = New System.Drawing.Size(280, 176)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.btnCancel)
        Me.Controls.Add(Me.btnOK)
        Me.Controls.Add(Me.txtPWord)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.cbUser)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "PW"
        Me.ShowInTaskbar = False
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Enter Password"
        Me.ResumeLayout(False)

    End Sub

#End Region

#Region "Form"

#Region "Buttons and Events"

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Dispose()
    End Sub 'btnCancel_Click

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click

        User = cbUser.Text
        If User = "" Then Exit Sub

        Static i As Int16
        If cbUser.Text = "Administrator" Then
            If txtPWord.Text = "abcdef" Then
                PWord = txtPWord.Text
                Visible = False
                'LogInToDatabase("In")
                LoggedIn = True ''Boolean passed throughout program.
                [b]LoadBio()'''this is where you open your main form[/b]

                Exit Sub
            End If
        End If
        PWord = GetPassword()

        If i >= 3 Then End
        If txtPWord.Text = PWord Then
            If cbUser.Text = "Administrator" Then
                PWord = "abcdef"
            End If

            Visible = False
            'LogInToDatabase("In")
            LoggedIn = True
            [b]LoadBio()'''this is where you open your main form[/b]

        Else

            Select Case i
                Case 0
                    If MessageBox.Show("That's strike one" & vbNewLine _
                         & "Would you like to try again?", "Logon", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
                        txtPWord.Text = String.Empty
                        txtPWord.Focus()
                    Else
                        End
                    End If
                Case 1
                    If MessageBox.Show("That's strike two" & vbNewLine _
                         & "Would you like to try again?", "Logon", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
                        txtPWord.Text = String.Empty
                        txtPWord.Focus()
                    Else
                        End
                    End If
                Case 2
                    MessageBox.Show("Strike 3!  You're out!", "Logon", MessageBoxButtons.OK, MessageBoxIcon.Question)
                    End
            End Select
            i += 1
        End If


    End Sub 'btnOK_Click

    Private Sub cbUser_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cbUser.KeyUp
        Select Case e.KeyCode
            Case Keys.Tab
                cbUser.DroppedDown = False
                txtPWord.Focus()
            Case Keys.Enter
                cbUser.DroppedDown = False
                txtPWord.Focus()
            Case Else
                cbUser.DroppedDown = True
        End Select
    End Sub 'cbUser_KeyUp

    Private Sub PW_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Cursor = Cursors.WaitCursor
        LoadUsers()
        Cursor = Cursors.Default
    End Sub 'PW_Load

#End Region

    Private Sub LoadUsers()
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim Con As ADODB.Connection
            Dim RS As ADODB.Recordset
            Dim SQL As String
            Dim strCon As String

            cbUser.Items.Clear()
            cbUser.Items.Add("Administrator")

            Con = New ADODB.Connection
            RS = New ADODB.Recordset

            strCon = "Provider=SQLOLEDB.1;Password=sa;Persist Security Info=True;" & _
                "User ID=sa;Initial Catalog=CatalogName;Data Source=ServerName"
            Con.Open(strCon)
            SQL = "SELECT UserName FROM SV_Online ORDER BY UserName"
            RS.Open(SQL, Con, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockBatchOptimistic, ADODB.CommandTypeEnum.adCmdText)

            Do While Not RS.EOF
                cbUser.Items.Add(RS(0).Value)
                RS.MoveNext()
            Loop

            Me.Cursor = Cursors.Default
            RS.Close()
            Con.Close()
            RS = Nothing
            Con = Nothing
        Catch ex As System.Exception
            MessageBox.Show("You have encountered an error!" & vbCrLf & "Your Users did not load!", "Information Services", MessageBoxButtons.OK, MessageBoxIcon.Error)
            SendErrorMessage("Get Password " & vbCrLf & CName & vbCrLf & ex.Message)
        End Try
    End Sub 'LoadUsers

#End Region

End Class

Code:
#Region "Password Form"

    Public Function GetPassword() As String

        Try
            Dim Con As ADODB.Connection
            Dim RS As ADODB.Recordset
            Dim SQL As String
            Dim i As Int16
            Con = New ADODB.Connection
            RS = New ADODB.Recordset
            Dim strCon As String
            strCon = "Provider=SQLOLEDB.1;Password=sa;Persist Security Info=True;" & _
                "User ID=sa;Initial Catalog=ThreeSource;Data Source=D5PH4J61"
            Con.Open(strCon)
            SQL = "SELECT UserName, UserPWord FROM SV_Online " & _
                "WHERE (UserName = '" & User & "')"
            RS.Open(SQL, Con, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockBatchOptimistic, ADODB.CommandTypeEnum.adCmdText)

            Do While Not RS.EOF
                PWord = RS(1).Value
                RS.MoveNext()
            Loop
            PWord = DecryptPass(PWord)
            Return PWord

            RS.Close()
            Con.Close()
            RS = Nothing
            Con = Nothing
        Catch ex As System.Exception
            MessageBox.Show("You have encountered an error!" & vbCrLf & "Your Login did not work!", "Information Services", MessageBoxButtons.OK, MessageBoxIcon.Error)
            SendErrorMessage("Get Password " & vbCrLf & CName & vbCrLf & ex.Message)
        End Try
    End Function 'GetPassword

    Public Function DecryptPass(ByVal strPass As String) As String
        Dim nLoopCnt, nAsc As Integer
        Dim strEncrypted, strChar, strReturn As String

        strEncrypted = Trim(strPass)
        nLoopCnt = 1
        Do While nLoopCnt < Len(strEncrypted) + 1
            strChar = Mid(strEncrypted, nLoopCnt, 1)
            nAsc = Asc(strChar)
            If nAsc > 30 And nAsc < 71 Then
                nAsc = nAsc + 40
            ElseIf nAsc > 70 And nAsc < 111 Then
                nAsc = nAsc - 40
            ElseIf nAsc > 110 And nAsc < 151 Then
                nAsc = nAsc + 40
            ElseIf nAsc > 150 And nAsc < 191 Then
                nAsc = nAsc - 40
            ElseIf nAsc > 190 And nAsc < 223 Then
                nAsc = nAsc + 33
            ElseIf nAsc > 222 And nAsc < 256 Then
                nAsc = nAsc - 33
            End If
            strChar = Chr(nAsc)
            strReturn = strReturn & strChar
            nLoopCnt = nLoopCnt + 1
        Loop

        DecryptPass = strReturn

    End Function 'DecryptPass

    Public Sub LogInToDatabase(ByVal InOut As String)
        Try
            Dim Con As ADODB.Connection
            Dim SQL As String
            Dim i As Int16
            Dim strCon As String
            Con = New ADODB.Connection

            strCon = "Provider=SQLOLEDB.1;Password=sa;Persist Security Info=True;" & _
                "User ID=sa;Initial Catalog=ThreeSource;Data Source=D5PH4J61"

            Con.Open(strCon)

            SQL = "INSERT INTO SV_Login (UserName, ComputerName, lDate, lTime, LogOffOn) " & _
                "VALUES('" & User & "','" & CName & "','" & Today & "','" & DateAndTime.TimeOfDay.ToShortTimeString & "','" & InOut & " ')"
            Con.Execute(SQL)
            Con.Close()
            Con = Nothing
        Catch ex As System.Exception
            MessageBox.Show("You have encountered an error!" & vbCrLf & "Your Login did not work!", "Information Services", MessageBoxButtons.OK, MessageBoxIcon.Error)
            SendErrorMessage("LogInToDatabase " & vbCrLf & CName & vbCrLf & ex.Message)
        End Try

    End Sub 'LogInToDatabase

#End Region 'Password Form

I hope that this helps.

Hint: SendErrorMessage is an automated Outlook send on all errors. I'm sure you'll tweak this as necessary.


Ron Repp

If gray hair is a sign of wisdom, then I'm a genius.
 
hiding the form isn't smart.
Because if I hide the Login form and the in main form the user clicks the close button at the next to the maximize button. The application isn't closed.

 
Right click on your project
Go to the Application Tab of your project
Under "Shutdown mode:"
Select "when last form closes"

Just make sure you show your forms before closing them.

-The answer to your problem may not be the answer to your question.
 
I see some people doing this and I cannot figure why:

The intention is to open another form on a certain button's Click Event.

Public Sub SomeEvent()

Dim frm1 as New Form1

frm1.Show()

frm1 = nothing

End Sub

Why do they set the Instance of the Form to Nothing when they have just showed the form?
The Form cannot possibly be referenced elsewhere or ramain live when they do? Is this the right way of doing it? I thought you would only set frm1 to Nothing when you Close the form and exit from it.

Len




Lennieboy -
Life is Good and God is Good
B-)
 
setting it to nothing is a step in the nudging the garbage collector to clean up.

As well, if you have something where you have to pull info off a form, that is not the form that you are working on, it is a good way to verify that you are pulling it off the right form.

-The answer to your problem may not be the answer to your question.
 
Sorry, but setting it to nothing will not convince the GC to clean it up. If it goes out of scope it will be cleaned up whether you set it to nothing or not. If something still holds a reference to it setting it to nothing will not convince the GC to clean it up.

BTW pulling data of a form that is not the form you are working on is not that good practice , lets remember MVP, MVC and other patterns.

Christiaan Baes
Belgium

"My old site" - Me
 
The neat thing about this is that setting frm1 to nothing right after frm1.show does not close the window, even when the method ends and the variable goes out of scope. frm1.dispose will however close the window and allow the garbage collector to reclaim the memory.

By setting frm1 to nothing, you are actually just getting rid of a pointer to the form. I suppose you might be saving a few bytes of memory on the stack by doing so, but the full form is still loaded on the heap. This makes a bit more sense on the C#/C++ side, but there is no real benefit to doing it. (Unless you are writing some sort of severely memory limited app where you need to push every byte you can into the heap, in which case... why are you using VB.Net?)

-Rick

VB.Net Forum forum796 forum855 ASP.NET Forum
[monkey]I believe in killer coding ninja monkeys.[monkey]
 
I am trying to find the logic in this here....

I now opened the form. It is live and loaded and working. It is running and I am filling the data in the form. It is live. How can I do all of this after I set the form to nothing? I have events that trigger in the background that actually need this form to be live in order to show data on a label.

And the only way for this to happen is for the the Event to pass the data to the label as indicated by the correct pointer....

I understand that setting the form to nothing indicates to the GC that the form is ready for disposal. But I do not want to dispose of the form while its live and running and doing things...

Only when I close the form do I want to do that....

Is my understanding here flawed?

Len

Lennieboy -
Life is Good and God is Good
B-)
 
I understand that setting the form to nothing indicates to the GC that the form is ready for disposal.

No it doesn't.

It is not because an object is nothing that all the references are gone.

The form is still live because it lifes on the heap, you just removed the stack reference so the form iniself is still alive. And everything on that form will still do what it is told. Only when you do this you will notice a
problem.

Code:
Dim frm1 as New Form1
frm1.Show()
frm1 = nothing
[red]frm1.show[/red]


Christiaan Baes
Belgium

"My old site" - Me
 
.Net uses two sections for memory. The Stack which holds only pointers (references) and primitive types (int, single, char, etc...). And the Heap which contains objects.

When you do this:
Code:
dim f as form
You are adding a reference to the stack, but that reference points to nothing.

When you do this:
Code:
dim f as New form
You are adding a reference to the stack, a form object to the heap, and setting the reference to point to the stack.

When you do this:
Code:
f = nothing
You are clearing the reference from the stack. At this point the form still exists in the heap though, but you can not access it using the variable f.

There are likely still other pointers to it (forms collection, application objects, etc...) and you could get a reference from the form itself (by throwing an event, or calling code that sets a reference to the calling object). In any case, it's usually easier to just not destroy f

When you do this:
Code:
f.dispose
The dispose method clears the form object from the heap (or atleast marks it for the garbage collector), and sets the reference f to point at nothing. That means that f still exists on the stack, but it just points at nothing. In most cases we don't really care about f sitting on the stack though because it only takes up a couple bytes and will get flagged for the GC as soon as it goes out of scope.

-Rick

VB.Net Forum forum796 forum855 ASP.NET Forum
[monkey]I believe in killer coding ninja monkeys.[monkey]
 
I had a slight type-o in there. After the second code block, the paragraph should read:

You are adding a reference to the stack, a form object to the heap, and setting the reference on the stack to point to the form on the heap.

-Rick

VB.Net Forum forum796 forum855 ASP.NET Forum
[monkey]I believe in killer coding ninja monkeys.[monkey]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top