一个关于toolbar的问题

voodoo82 2010-11-15 11:10:10
一个Form窗口,里面有一个ToolStrip控件,ToolStrip里面再添加一个button。

程序运行的时候,使另一个程序窗口为最前,这样Form失去焦点,然后点击ToolStrip中的button,只能使Form为最前,而button的click事件没有被引发。所以只能点击两次才能触发button的click事件。

而在Form为非最前时,点击Form窗体中的button,或者点击窗体右上角的关闭按钮,则一次点击就可以把Form送至最前并引发Click事件。

这个现象很奇怪,有人知道怎么解决吗?谢谢了。
...全文
73 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
lonyjianhui 2010-11-16
  • 打赏
  • 举报
回复
具体情况具体分析,LZ肯定代码有错,点击两次才能触发button的click事件这种情况是没可能出现的,除非Click事件是你自己写的,看看Click事件里你自己有没有加控制变量吧,或者发代码看看
熙风 2010-11-16
  • 打赏
  • 举报
回复
友情帮顶······
voodoo82 2010-11-16
  • 打赏
  • 举报
回复
在网上搜索了一下,找到了结果,结贴了。

解决方法如下:从ToolStrip派生类,重载WndProc函数,处理WM_MOUSEACTIVE消息。具体可见下面的代码


/// <summary>
/// This class is derived from ToolStrip. It is used to fix the problem that
/// buttons in toolstrip can't get Click event if user click them when the form
/// is not focused.
/// </summary>
class ToolStripEx
: ToolStrip
{
private const uint WM_MOUSEACTIVATE = 0x21;
private const uint MA_ACTIVATE = 1;
private const uint MA_ACTIVATEANDEAT = 2;
private const uint MA_NOACTIVATE = 3;
private const uint MA_NOACTIVATEANDEAT = 4;

/// <summary>
/// This field is used to control whether buttons in ToolStrip get Click event
/// when the form is not focused.
///
/// Type : System.Boolean
///
/// false is the same behavior provided by the base ToolStrip class
/// true is that buttons can get Click event even the form is not focused
/// Default value is false
/// </summary>
private bool _clickThrough = false;

/// <summary>
/// This property is used to control whether buttons in ToolStrip get Click event
/// when the form is not focused.
///
/// Type : System.Boolean
///
/// false is the same behavior provided by the base ToolStrip class
/// true is that buttons can get Click event even the form is not focused
/// Default value is false
/// </summary>
public bool ClickThrough
{
get { return _clickThrough; }
set { _clickThrough = value; }
}

protected override void WndProc(ref Message m)
{
base.WndProc(ref m);

if (_clickThrough &&
m.Msg == WM_MOUSEACTIVATE &&
m.Result == (IntPtr)MA_ACTIVATEANDEAT)
{
m.Result = (IntPtr)MA_ACTIVATE;
}
}
}
voodoo82 2010-11-16
  • 打赏
  • 举报
回复
我没有任何加任何代码,只是拖些空间到窗体,然后加个Click函数

请看清楚我的条件,是窗口在后台,然后点击ToolBar里按钮,这时不能触发Click事件,只能让窗口跳到前台。

而窗体上的按钮,就可以直接让窗口跳前台,并且出发Click事件

110,502

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧