LoginSignup
10
7

More than 5 years have passed since last update.

ListBoxの全項目を高速に選択する

Posted at

ListBoxの全項目を選択したいとする。
selectall.png

SelectAll的なメソッドは存在しないので、自前で頑張る必要がある。

素朴な実装(これはダメ)

素朴な実装
for (int i = 0; i < listBox1.Items.Count; i++)
{
    listBox1.SetSelected(i, true);
}

ぱっと思いつくのがこの方法だが、残念ながら、遅い。

Windows APIを使ってみる

宣言
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
private const int LB_SETSEL = 0x185;
処理
SendMessage(listBox1.Handle, LB_SETSEL, 1, -1);
listBox1.SetSelected(0, true);

Windows APIを使って全選択メッセージを直接送ってやる方法だ。これなら一瞬だ。

SendKeysしてみる

先述の方法で充分なのだが、もっと簡単に一行で済ます方法もある。

SendKeys
SendKeys.SendWait("{HOME}+{END}");

HOMEキーで先頭を選択し、SHIFTキーを押しながらENDキーで最終項目まで選択するという操作を再現している。これも一瞬だ。
予め全選択したいコントロールにフォーカスが合っている必要がある。

(この記事は昔書いた記事から余計な演出と遠回りを省いて再掲したものです。)

10
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
7