Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I programmatically manipulate Anchor styles?

You can do this using the bitwise operators. In C# the bitwise operators are &, | and ^; in VB they are And (or &), Or and Xor (or ^). Here is code that will toggle whether label1 is anchored on the left.

[C#]

using System.Windows.Forms;

private void button1_Click( object sender, System.EventArgs e )
{
  if ( (label1.Anchor & AnchorStyles.Left) != 0 ) // test if anchored on left
    label1.Anchor ^= AnchorStyles.Left; // remove anchor
  else
    label1.Anchor |= AnchorStyles.Left; // add anchor
}

[Visual Basic]

Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
  If Label1.Anchor And AnchorStyles.Left Then ' test if anchored on left
    Label1.Anchor = Label1.Anchor Xor AnchorStyles.Left ' remove anchor
  Else
    Label1.Anchor = Label1.Anchor Or AnchorStyles.Left ' add anchor
  End If
End Sub

Contributed from George Shepherd's Windows Forms FAQ



Page view counter