我正在使用旧版 MainMenu control (with MenuItem s) control in an application, and would like to implement zoom in and zoom out menu items (with Control++ 和 Control+- 键盘快捷键)。 (请注意,我使用的是 MainMenu 而不是 MenuStrip )。 MenuItem 确实有一个 Shortcut属性,类型 Shortcut , 但它没有 CtrlPlus 选项。
我决定看看如何Shortcut was implemented in the referencesource ,看起来每个枚举值只是几个 Keys 的组合枚举值(例如 CtrlA 只是 Keys.Control + Keys.A)。所以我尝试创建一个应该等于 Control+Plus 的自定义快捷键值:
const Shortcut CONTROL_PLUS = (Shortcut)(Keys.Control | Keys.Oemplus);
zoomInMenuItem.Shortcut = CONTROL_PLUS;
但是,当我尝试分配 Shortcut 属性时,这会引发 InvalidEnumArgumentException。
所以我决定使用反射,并修改(非公开)MenuItemData的 shortcut 属性,然后调用(非公开)UpdateMenuItem方法。这实际上有效(具有在菜单项中显示为 Control+Oemplus 的副作用):
const Shortcut CONTROL_PLUS = (Shortcut)(Keys.Control | Keys.Oemplus);
var dataField = typeof(MenuItem).GetField("data", BindingFlags.NonPublic | BindingFlags.Instance);
var updateMenuItemMethod = typeof(MenuItem).GetMethod("UpdateMenuItem", BindingFlags.NonPublic | BindingFlags.Instance);
var menuItemDataShortcutField = typeof(MenuItem).GetNestedType("MenuItemData", BindingFlags.NonPublic)
.GetField("shortcut", BindingFlags.NonPublic | BindingFlags.Instance);
var zoomInData = dataField.GetValue(zoomInMenuItem);
menuItemDataShortcutField.SetValue(zoomInData, CONTROL_PLUS);
updateMenuItemMethod.Invoke(zoomInMenuItem, new object[] { true });
虽然该方法有效,但它使用了反射,我不确定它是否面向 future 。
我正在使用 MenuItem而不是更新的ToolStripMenuItem因为我需要拥有 RadioCheck 属性(以及其他原因);放弃它不是一种选择。
下面是创建上述对话框的一些完整代码,显示了我要完成的工作(最相关的代码在 OnLoad 方法中):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace ZoomMenuItemMCVE
{
public partial class ZoomForm : Form
{
private double zoom = 1.0;
public double Zoom {
get { return zoom; }
set {
zoom = value;
zoomTextBox.Text = "Zoom: " + zoom;
}
}
public ZoomForm() {
InitializeComponent();
}
protected override void OnLoad(EventArgs e) {
const Shortcut CONTROL_PLUS = (Shortcut)((int)Keys.Control + (int)Keys.Oemplus);
const Shortcut CONTROL_MINUS = (Shortcut)((int)Keys.Control + (int)Keys.OemMinus);
base.OnLoad(e);
//We set menu later as otherwise the designer goes insane (http://stackoverflow.com/q/28461091/3991344)
this.Menu = mainMenu;
var dataField = typeof(MenuItem).GetField("data", BindingFlags.NonPublic | BindingFlags.Instance);
var updateMenuItemMethod = typeof(MenuItem).GetMethod("UpdateMenuItem", BindingFlags.NonPublic | BindingFlags.Instance);
var menuItemDataShortcutField = typeof(MenuItem).GetNestedType("MenuItemData", BindingFlags.NonPublic)
.GetField("shortcut", BindingFlags.NonPublic | BindingFlags.Instance);
var zoomInData = dataField.GetValue(zoomInMenuItem);
menuItemDataShortcutField.SetValue(zoomInData, CONTROL_PLUS);
updateMenuItemMethod.Invoke(zoomInMenuItem, new object[] { true });
var zoomOutData = dataField.GetValue(zoomOutMenuItem);
menuItemDataShortcutField.SetValue(zoomOutData, CONTROL_MINUS);
updateMenuItemMethod.Invoke(zoomOutMenuItem, new object[] { true });
}
private void zoomInMenuItem_Click(object sender, EventArgs e) {
Zoom *= 2;
}
private void zoomOutMenuItem_Click(object sender, EventArgs e) {
Zoom /= 2;
}
}
}
namespace ZoomMenuItemMCVE
{
partial class ZoomForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.components = new System.ComponentModel.Container();
System.Windows.Forms.MenuItem viewMenuItem;
this.zoomTextBox = new System.Windows.Forms.TextBox();
this.mainMenu = new System.Windows.Forms.MainMenu(this.components);
this.zoomInMenuItem = new System.Windows.Forms.MenuItem();
this.zoomOutMenuItem = new System.Windows.Forms.MenuItem();
viewMenuItem = new System.Windows.Forms.MenuItem();
this.SuspendLayout();
//
// zoomTextBox
//
this.zoomTextBox.Dock = System.Windows.Forms.DockStyle.Bottom;
this.zoomTextBox.Location = new System.Drawing.Point(0, 81);
this.zoomTextBox.Name = "zoomTextBox";
this.zoomTextBox.ReadOnly = true;
this.zoomTextBox.Size = new System.Drawing.Size(292, 20);
this.zoomTextBox.TabIndex = 0;
this.zoomTextBox.Text = "Zoom: 1.0";
//
// mainMenu
//
this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
viewMenuItem});
//
// viewMenuItem
//
viewMenuItem.Index = 0;
viewMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.zoomInMenuItem,
this.zoomOutMenuItem});
viewMenuItem.Text = "View";
//
// zoomInMenuItem
//
this.zoomInMenuItem.Index = 0;
this.zoomInMenuItem.Text = "Zoom in";
this.zoomInMenuItem.Click += new System.EventHandler(this.zoomInMenuItem_Click);
//
// zoomOutMenuItem
//
this.zoomOutMenuItem.Index = 1;
this.zoomOutMenuItem.Text = "Zoom out";
this.zoomOutMenuItem.Click += new System.EventHandler(this.zoomOutMenuItem_Click);
//
// ZoomForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 101);
this.Controls.Add(this.zoomTextBox);
this.Name = "ZoomForm";
this.Text = "ZoomForm";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.TextBox zoomTextBox;
private System.Windows.Forms.MenuItem zoomInMenuItem;
private System.Windows.Forms.MenuItem zoomOutMenuItem;
}
}
上面的代码可以正常工作,并且做了我想要的,但我不确定这样做是否正确(使用反射修改私有(private)变量通常看起来是不正确的方法)。我的问题是:
最佳答案
it uses reflection, and I'm not sure if it's future-proof
你会侥幸逃脱的,在引擎盖下没有发生特别危险的事情。 MainMenu/MenuItem 类是一成不变的,永远不会再改变。您是面向 future 的 Windows 版本,此快捷方式实际上并未由 Windows 实现,但已添加到 MenuItem。实际上是 Form.ProcessCmdKey() 方法使它起作用。这是你在不修改菜单项的情况下做的提示。将此代码粘贴到您的表单类中:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == (Keys.Control | Keys.Oemplus)) {
zoomInMenuItem.PerformClick();
return true;
}
if (keyData == (Keys.Control | Keys.OemMinus)) {
zoomOutMenuItem.PerformClick();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
你得到的快捷键描述很糟糕,没有正常人知道“Oemplus”可能意味着什么。不要使用自动生成的,写你自己的。你不能用设计器做到这一点,它不会让你在项目文本和快捷键描述之间输入制表符。但是代码没有问题:
public ZoomForm() {
InitializeComponent();
zoomInMenuItem.Text = "Zoom in\tCtrl +";
zoomOutMenuItem.Text = "Zoom out\tCtrl -";
}
I'm using MenuItem and not the newer ToolStripMenuItem because...
这不是一个很好的理由。 ToolStripMenuItem 确实没有为单选按钮行为提供开箱即用的实现,但您自己添加它非常容易。 Winforms 使创建您自己的 ToolStrip 项目类变得简单,这些项目类在设计时可用,并且可以按照您在运行时选择的方式运行。向您的项目添加一个新类并粘贴如下所示的代码。编译。在设计时使用 Insert > RadioItem 上下文菜单项插入一个,Edit DropdownItems... 上下文菜单项可以轻松添加多个。您可以设置 Group 属性来指示哪些项目属于一起并且应该作为一个单选组。
using System;
using System.Windows.Forms;
using System.Windows.Forms.Design;
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.MenuStrip | ToolStripItemDesignerAvailability.ContextMenuStrip)]
public class ToolStripRadioItem : ToolStripMenuItem {
public int Group { get; set; }
protected override void OnClick(EventArgs e) {
if (!this.DesignMode) {
this.Checked = true;
var parent = this.Owner as ToolStripDropDownMenu;
if (parent != null) {
foreach (var item in parent.Items) {
var sibling = item as ToolStripRadioItem;
if (sibling != null && sibling != this and sibling.Group == this.Group) sibling.Checked = false;
}
}
}
base.OnClick(e);
}
}
关于c# - 使用 Control+Plus 的快捷方式创建 MenuItem – 使用反射修改 MenuItem 的私有(private)字段是最好的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30197697/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..