C# 如何为列表框中的选定项着色?单击鼠标右键时仅为选定项目文本着色
一般来说,它可以工作,但由于我只想在右键单击鼠标右键时使其为项目着色,因此它不工作,因为当我显示/打开列表框时,它首先进入DrawItem事件:C# 如何为列表框中的选定项着色?单击鼠标右键时仅为选定项目文本着色,c#,C#,一般来说,它可以工作,但由于我只想在右键单击鼠标右键时使其为项目着色,因此它不工作,因为当我显示/打开列表框时,它首先进入DrawItem事件: private void listBox1_MouseDown(object sender, MouseEventArgs e) { listBox1.SelectedIndex = listBox1.IndexFromPoint(e.X, e.Y); if (e.Button == S
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
listBox1.SelectedIndex = listBox1.IndexFromPoint(e.X, e.Y);
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
isColor = true;
}
}
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (isColor == true)
{
if (e.Index < 0) return;
//if the item state is selected them change the back color
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
e = new DrawItemEventArgs(e.Graphics,
e.Font,
e.Bounds,
e.Index,
e.State ^ DrawItemState.Selected,
e.ForeColor,
Color.Red);//Choose the color
// Draw the background of the ListBox control for each item.
e.DrawBackground();
// Draw the current item text
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
// If the ListBox has focus, draw a focus rectangle around the selected item.
e.DrawFocusRectangle();
}
}
private void listBox1\u MouseDown(对象发送方,MouseEventArgs e)
{
listBox1.SelectedIndex=listBox1.IndexFromPoint(e.X,e.Y);
if(e.Button==System.Windows.Forms.MouseButtons.Right)
{
isColor=true;
}
}
私有void listBox1_DrawItem(对象发送方,DrawItemEventArgs e)
{
如果(isColor==true)
{
如果(e.指数<0)返回;
//如果选择了项目状态,则会更改背景颜色
if((e.State&DrawItemState.Selected)=DrawItemState.Selected)
e=新的DrawItemEventArgs(如图形、,
e、 字体,
e、 界限,
e、 索引,
e、 状态^DrawItemState。已选择,
e、 前景色,
颜色。红色);//选择颜色
//为每个项目绘制ListBox控件的背景。
e、 牵引杆接地();
//绘制当前项文本
e、 Graphics.DrawString(listBox1.Items[e.Index].ToString(),e.Font,Brush.Black,e.Bounds,StringFormat.GenericDefault);
//如果列表框具有焦点,请围绕选定项绘制一个焦点矩形。
e、 DrawFocusRectangle();
}
}
我使用了一个标志isColor,但是由于它是第一次进入DrawItem事件,所以这段代码不能正常工作。
因为iColor现在是第一次使用
编辑:
我还需要两样东西
对列表中的每个项调用OnDrawItem。你把每件东西都涂成红色。您需要检查需要绘制的项目是否为所选项目(如果我记得正确,则为
e.selected
),如果为红色,则为其他颜色。。可能是SystemColors.Window
尝试以下操作:
if(((ListBox)sender).SelectedIndex == e.index)
{
....
}
是否为列表中的每个项目运行DrawItem?您需要捕获单击的项目,并使用逻辑检查当前正在绘制的项目是否与单击的项目相同…keyboardP dupilcated链接示例正在运行。问题是,我只想在用户用鼠标右键单击某个项目时为每个项目着色。所以我尝试使用一个标志,但问题是当我显示/打开列表框时,它首先进入DrawItem事件。我刚刚用它更新了我的问题。