Close is a Custom Button I made.

    Dim CloseButton As New Close

    Private Sub CloseButtonCode() Handles Me.Load
        CloseButton.Anchor = AnchorStyles.Top And AnchorStyles.Right
        CloseButton.Enabled = True
        CloseButton.Location = New Point(1170, 0)
        CloseButton.Size = New Size(30, 30)
        CloseButton.Visible = True
        Controls.Add(CloseButton)
        AddHandler CloseButton.Click, AddressOf CloseButtonClick
    End Sub

Whenever I Maximise, this button doesn't move to the top right corner like it's supposed to. Any help? Thanks in advance.

Dani AI

Generated

Short answer: was on the right track — combine the Anchor flags instead of using And. The easiest, correct way is to set the control to be anchored to the top and right so its distance to the right edge is preserved when the form is resized.

A quick explanation: AnchorStyles is a flags enum. Using a bitwise intersection (And) between two different flags produces zero, which effectively clears anchoring. Using the bitwise OR operator combines the flags so the control stays pinned to both edges. Also watch for the custom Close control itself: if its constructor or designer code sets Anchor later, that will overwrite what you set in the form. Verify the final Anchor value in the debugger after the form loads.

If you prefer to position it manually (or your custom control needs special handling), update its Left in the form Resize event instead of relying on Anchor:

CloseButton.Anchor = AnchorStyles.Top Or AnchorStyles.Right
Private Sub Form1_Resize(sender As Object, e As EventArgs) Handles Me.Resize
    CloseButton.Left = Me.ClientSize.Width - CloseButton.Width - 10
End Sub

For reference on behavior and correct usage see the Control.Anchor property and the AnchorStyles enum in the Microsoft docs: Control.Anchor property and AnchorStyles enumeration.

Recommended Answers

All 2 Replies

Oh friend, that was a simple one. Here's a help:

CloseButton.Anchor = AnchorStyles.Top + AnchorStyles.Right

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.