共用方式為


CA1301: Avoid duplicate accelerators

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
RuleId CA1301
Category Microsoft.Globalization
Breaking change Non-breaking

Cause

A type extends System.Windows.Forms.Control and contains two or more top-level controls that have identical access keys that are stored in a resource file.

Rule description

An access key, also known as an accelerator, enables keyboard access to a control by using the Alt key. When multiple controls have the same access key, the behavior of the access key is not well defined. The user might not be able to access the intended control by using the access key, and a control other than the one that is intended might be enabled.

The current implementation of this rule ignores menu items. However, menu items in the same submenu should not have identical access keys.

How to fix violations

To fix a violation of this rule, define unique access keys for all controls.

When to suppress warnings

Do not suppress a warning from this rule.

Example

The following example shows a minimal form that contains two controls that have identical access keys. The keys are stored in a resource file, which is not shown. However, their values appear in the commented out checkBox.Text lines. The behavior of duplicate accelerators can be examined by exchanging the checkBox.Text lines with their commented out counterparts. However, in this case, the example will not generate a warning from the rule.

using System;
using System.Drawing;
using System.Resources;
using System.Windows.Forms;

namespace GlobalizationLibrary
{
   public class DuplicateAccelerators : Form
   {
      [STAThread]
      public static void Main()
      {
         DuplicateAccelerators accelerators = new DuplicateAccelerators();
         Application.Run(accelerators);
      }

      private CheckBox checkBox1;
      private CheckBox checkBox2;

      public DuplicateAccelerators()
      {
         ResourceManager resources = 
            new ResourceManager(typeof(DuplicateAccelerators));

         checkBox1 = new CheckBox();
         checkBox1.Location = new Point(8, 16);
         // checkBox1.Text = "&checkBox1";
         checkBox1.Text = resources.GetString("checkBox1.Text");

         checkBox2 = new CheckBox();
         checkBox2.Location = new Point(8, 56);
         // checkBox2.Text = "&checkBox2";
         checkBox2.Text = resources.GetString("checkBox2.Text");

         Controls.Add(checkBox1);
         Controls.Add(checkBox2);
      }
   }
}

See also