我如何创建一个";“不可聚焦”;用C#表示的形式?
我希望在C#中创建一个不能接受焦点的表单,即当我单击表单上的按钮时,焦点不会从当前具有焦点的应用程序中窃取 有关此示例,请参见Windows屏幕键盘。请注意,单击按钮时,焦点不会从当前使用的应用程序中获取 我如何实现这种行为 更新: 事实证明,只需覆盖我如何创建一个";“不可聚焦”;用C#表示的形式?,c#,.net,winforms,C#,.net,Winforms,我希望在C#中创建一个不能接受焦点的表单,即当我单击表单上的按钮时,焦点不会从当前具有焦点的应用程序中窃取 有关此示例,请参见Windows屏幕键盘。请注意,单击按钮时,焦点不会从当前使用的应用程序中获取 我如何实现这种行为 更新: 事实证明,只需覆盖CreateParams属性并将WS_EX_NOACTIVATE添加到扩展窗口样式中即可。谢谢你给我指明了正确的方向 不幸的是,这有一个不希望出现的副作用,即它会干扰窗体的移动,即您仍然可以在屏幕周围拖放窗体,但拖动时窗口的边框不会显示,因此很难精
CreateParams
属性并将WS_EX_NOACTIVATE
添加到扩展窗口样式中即可。谢谢你给我指明了正确的方向
不幸的是,这有一个不希望出现的副作用,即它会干扰窗体的移动,即您仍然可以在屏幕周围拖放窗体,但拖动时窗口的边框不会显示,因此很难精确定位窗体
如果有人知道如何解决这个问题,我们将不胜感激。要禁用鼠标激活:
class NonFocusableForm : Form
{
protected override void DefWndProc(ref Message m)
{
const int WM_MOUSEACTIVATE = 0x21;
const int MA_NOACTIVATE = 0x0003;
switch(m.Msg)
{
case WM_MOUSEACTIVATE:
m.Result = (IntPtr)MA_NOACTIVATE;
return;
}
base.DefWndProc(ref m);
}
}
要在没有激活的情况下显示表单(在无边界表单的情况下,唯一一种对我有效的方法):
执行此操作的标准方法(似乎并不适用于所有表单样式):
如果有其他激活表单的方法,可以以类似的方式抑制它们。这是我使用的“NoFocusForm”:
公共类NoFocusForm:Form
{
///来自MSDN
///使用此样式创建的顶级窗口不会成为
///当用户单击前台窗口时,系统不会显示该窗口
///当用户最小化或
///关闭前景窗口。不应激活该窗口
///通过编程访问或通过键盘导航访问
///技术,如“讲述人”。要激活窗口,请使用
///SetActiveWindow或SetForegroundWindow函数。该窗口没有
///默认情况下显示在任务栏上。强制窗口显示在任务栏上
///在任务栏上,使用WS_EX_APPWINDOW样式。
私有常量int WS_EX_NOACTIVATE=0x08000000;
公共NoFocusForm()
{
//我的其他东西
}
///
///阻止窗体获得焦点
///
受保护的重写CreateParams CreateParams
{
得到
{
var createParams=base.createParams;
createParams.ExStyle |=WS_EX_NOACTIVATE;
返回createParams;
}
}
}
不幸的是,虽然这会阻止窗体在单击时聚焦,但不会阻止最后一个应用程序失去焦点。感谢您为我指出正确的解决方案。@jnm2检查我对原始问题的编辑-您想要WS\u EX\u NOACTIVATE
扩展窗口样式。谢谢事实证明,我需要在表单上的所有按钮上同时使用SetStyle(ControlStyles.selective,false)
,这样就可以在.NET winforms没有决定使用SetFocus
响应WM\u MOUSEDOWN
的情况下单击这些按钮。可能的重复
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr handle, int flags);
NativeMethods.ShowWindow(form.Handle, 8);
protected override bool ShowWithoutActivation
{
get { return true; }
}
public class NoFocusForm : Form
{
/// From MSDN <see cref="https://docs.microsoft.com/en-us/windows/win32/winmsg/extended-window-styles"/>
/// A top-level window created with this style does not become the
/// foreground window when the user clicks it. The system does not
/// bring this window to the foreground when the user minimizes or
/// closes the foreground window. The window should not be activated
/// through programmatic access or via keyboard navigation by accessible
/// technology, such as Narrator. To activate the window, use the
/// SetActiveWindow or SetForegroundWindow function. The window does not
/// appear on the taskbar by default. To force the window to appear on
/// the taskbar, use the WS_EX_APPWINDOW style.
private const int WS_EX_NOACTIVATE = 0x08000000;
public NoFocusForm()
{
// my other initiate stuff
}
/// <summary>
/// Prevent form from getting focus
/// </summary>
protected override CreateParams CreateParams
{
get
{
var createParams = base.CreateParams;
createParams.ExStyle |= WS_EX_NOACTIVATE;
return createParams;
}
}
}