How do I set the default menu item in a ContextMenuStrip? - c#

In my application I am using a popup menu item when right clicking an object. I dynamically build up this menu using code like this:
ContextMenuStrip menu = new ContextMenuStrip();
menu.Items.Add(new ToolStripMenuItem("Item1", aNiceImage, someFunction));
menu.Items.Add(new ToolStripMenuItem("Item2", alsoNiceImage, someOtherFunction));
Now I want to set one of these menu items in bold (as it is recommended by the Windows User Experience Guidelines) to indicate which action corresponds with double clicking the object.
How do I do this?

use item.Font = new Font(item.Font, item.Font.Style | FontStyle.Bold) to make bold effect to the current font.
you can also auto select the default item as follows:
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
contextMenuStrip1.Items[3].Select();
}

Use the Font property to specify a font with the desired FontStyle:
myToolStripMenuItem.Font = new Font(
FontFamily.GenericSansSerif,
12.0F, FontStyle.Bold);
Obviously altering the inputs for the desired output, FontStyle.Bold being the important part here.

Related

How to capture selected values from a dialog?

I created a FontDialog.cs Windows Form where my users can choose colors among other things for the text. I need to capture what the user has selected on the dialog:
Here's how I'm calling the dialog:
DialogsTestingGrounds.FontDialog dialog = new FontDialog();
dialog.ShowDialog();
How can I capture the selected values, I imagine I have to create properties for everything I want to transfer on the FontDialog.cs form end, right?
What you would want to do is expose properties on your FontDialog that make the values available. You could then use dialog.PropertyName to reference it by the name of the property.
It is not necessary, you can use, ie, dialog.Font to get the selected font,
dialog.Color for the color and so on...
Mitchel's answer will work but you might want to incorporate a couple other items along the same line.
Have a public property (per Mitchel's
answer).
Have a public constructor on your
form with the type of the property as
an argument so you can pass in the value
in question (this would allow you have the dialog prepopulated with old selection).
Surround your call to your dialog
with a check for dialogresult so you
only change the value when the user
wants to. (note the process for this is different in WPF)
Felice is also right in that you
don't really need to create a new
font dialog if the only thing you
care about is the font. There is a
built in font dialog in .Net
http://msdn.microsoft.com/en-us/library/system.windows.forms.fontdialog%28v=vs.71%29.aspx
So the internals of your dialog class may look like this psuedo code.
public Font SelectedFont { get; set; }
public FontDialog()
{
//set your defaults here
}
public FontDialog (Font font)
{
SelectedFont = font;
//dont forget to set the passed in font to your ui values here
}
private void acceptButton_Click(object sender, EventArgs e)
{
SelectedFont = //How ever you create your font object;
}
Then to call your function (assumes the the acceptButton above is the forms AcceptButton)
DialogsTestingGrounds.FontDialog dialog = new FontDialog();
if(dialog.ShowDialog() == DialogResult.OK)
//Do Something

Creating a font dialog. How can I display each font with its design?

Here's my code:
private void DialogFont_Load(object sender, EventArgs e)
{
LoadInstalledFonts();
}
private void LoadInstalledFonts()
{
var fontCollection = new System.Drawing.Text.InstalledFontCollection();
foreach (var font in fontCollection.Families)
{
lstFonts.Items.Add(font.Name);
}
}
How can I display each font using its own design, sort of like a preview of the fonts? I'm using the ListBox control to list the fonts.
You can do it easily in WPF.
The XAML would look like:
<ComboBox Width="100" Height="30" x:Name="FontSelector">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" FontFamily="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
And C# codebehind:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
FontSelector.ItemsSource = Fonts.SystemFontFamilies;
}
You could also check this article over on CodeProject which walks through (in a Winforms example) how to populate a list box with fonts like you want: http://www.codeproject.com/KB/selection/FontListBoxAndCombo.aspx
Maybe go with a ListView instead of a ListBox? The ListViewItem type has a Font property you could use. I'm not aware of any special per-item formatting capabilities of ListBox.
Update: In case you're still working on this, here's a snippet of some code that worked for me (this won't compile as-is as it's just a clip from a larger user control; I'm sure you can figure out what goes where though):
private void PopulateListView(IEnumerable<FontFamily> fontFamilies)
{
try
{
m_listView.BeginUpdate();
float fontSize = m_listView.Font.Size;
Color foreColor = m_listView.ForeColor;
Color backColor = m_listView.BackColor;
string sampleText = m_sampleText;
foreach (FontFamily fontFamily in fontFamilies)
{
var listViewItem = new ListViewItem(fontFamily.Name)
{
UseItemStyleForSubItems = false
};
var sampleSubItem = new ListViewItem.ListViewSubItem(listViewItem, sampleText, foreColor, backColor, new Font(fontFamily, fontSize));
listViewItem.SubItems.Add(sampleSubItem);
m_listView.Items.Add(listViewItem);
}
}
finally
{
m_listView.EndUpdate();
}
}
Here's what the result looks like:
First thing, I want to make sure that you are aware of the FontDialog control, and you are purposely wanting to create a custom Font Dialog. If you weren't aware of it, then maybe you can take a look at it and make sure that it doesn't fit your needs before trying to create your own. And the following Stack Overflow question shows you how to make sure it is populated with all the device fonts and not just TrueType fonts.
Now, if you still want to create your own, then the following is a simplified solution:
Add a Label to your Font Dialog and set its text to whatever you want the user to see as a sample of the font. Something like AabBcC, or it could even be a random sentence.
You can set the Font of the label in the SelectedIndexChanged event of your ListBox. This in effect changes the sample text to match the font you specify. The following is a simple example:
Note that you can also use a Textbox if you want your user to specify the text that they want to see in another font. Also, some fonts like Andy and Aharomi throw an ArgumentException stating that the Font doesn't support a regular style, so it would be wise to catch this exception type.
private void lstFonts_SelectedIndexChanged(object sender, EventArgs e)
{
lblSample.Font = new Font(lstFonts.SelectedItem.ToString(), 12);
}
Using a ListBox, I would think you'd need to do owner-draw. When drawing each list item, you'd need to select the font for that item.

tab control, vertically aligned tabs with vertically aligned text

I want to use a tab control and have the tabs displayed on the left, as opposed to at the top. I have set the alignment to the left and the tabs are displayed there. However, how do I get the text to be displayed on the tab, vertically? I have looked at the msdn and it gives an example of a left aligned tab control but the tab label is still displayed horisontally!
The other thing, does anybody know how to use the tab control with left aligned tabs with the default layout so that it looks better?
Please no third party apps unless they are free, and yes I have looked at code project already.
Thanks, R.
It is an age-old bug in the visual styles renderer for the native Windows tab control. It only supports tabs at the top, the Microsoft programmer that worked on it was run over by a bus before she could finish the job, I guess.
The only thing you can do about it is selectively turn off visual styles for the control. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form, replacing the original.
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class FixedTabControl : TabControl {
[DllImportAttribute("uxtheme.dll")]
private static extern int SetWindowTheme(IntPtr hWnd, string appname, string idlist);
protected override void OnHandleCreated(EventArgs e) {
SetWindowTheme(this.Handle, "", "");
base.OnHandleCreated(e);
}
}
If you create your own DrawItem event, you can manually write the tab headers. You could use this process:
1) Set the following properties of the TabControl:
Property | Value
----------|----------------
Alignment | Right (or left, depending on what you want)
SizeMode | Fixed
DrawMode | OwnerDrawFixed
2) Set the ItemSize.Width property to 25 and the ItemSize.Height property to 100. Adjust these values as you want, but remember that basically, the width is the height and vice versa.
3) Add an event handler for the DrawItem event and add the following code:
private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
{
Graphics g = e.Graphics;
Brush _TextBrush;
// Get the item from the collection.
TabPage _TabPage = tabControl1.TabPages[e.Index];
// Get the real bounds for the tab rectangle.
Rectangle _TabBounds = tabControl1.GetTabRect(e.Index);
if(e.State == DrawItemState.Selected)
{
// Draw a different background color, and don't paint a focus rectangle.
_TextBrush = new SolidBrush(Color.Red);
g.FillRectangle(Brushes.Gray, e.Bounds);
}
else
{
_TextBrush = new System.Drawing.SolidBrush(e.ForeColor);
e.DrawBackground();
}
// Use our own font. Because we CAN.
Font _TabFont = new Font("Arial", 10, FontStyle.Bold, GraphicsUnit.Pixel);
// Draw string. Center the text.
StringFormat _StringFlags = new StringFormat();
_StringFlags.Alignment = StringAlignment.Center;
_StringFlags.LineAlignment = StringAlignment.Center;
g.DrawString(_TabPage.Text, _TabFont, _TextBrush,
_TabBounds, new StringFormat(_StringFlags));
}
4) Profit!
(original source: http://en.csharp-online.net/TabControl)

Add tool tip on a column of Grid(Winforms) using ToolTip class and is it possible or not?

I want to add a tooltip using ToolTip class on a column of a grid in winforms.
I want this because I need to extend duration of builtin grid tooltip in radgridview. If you can help me in settings the time of builtin tooltip of grid then it would also be sufficient.
EDIT: Can anybody just tell me that is it possible or not?
Thanks.
It's possible to add a ToolTip to an existing control. I've never used radgridview, so I can only give you a general direction to head.
ToolTip tooltip = new ToolTip();
tooltip.SetToolTip(grid, "your caption here");
tooltip.Popup += HandleToolTipPopup;
tooltip.AutoPopDelay = {time to display tooltip};
private void HandleToolTipPopup(object sender, PopupEventArgs e)
{
Point mouseLocation = Control.MousePosition;
Point relativeLocation = grid.PointToClient(mouseLocation);
// Check to see if it is within the area to popup on.
// Set e.Cancel to false if not.
}

How do I set the Font color of a label to the same as the caption color of a GroupBox?

I want to have some labels on a form with the same font color as the caption on my group boxes, and furthermore I want these colors to change if the user has applied a different Theme on their system.
Can I do this without changing the GroupBox caption from its default?
UPDATE:
I have tried setting the Label ForeColor to ActiveCaption, this looks okay for the Default (Blue) scheme, but when I change the scheme to Olive Green, the label and group box captions are not the same.
Also, the GroupBox normal behaviour is that setting the FlatStyle to Standard sets the caption colour to ForeColor, however to create a new GroupBox and set its ForeColor to ControlText, you must first set it to something other than ControlText and then set it back again. (If you don't follow what I mean, then try it and see.)
Hmm, same question? I'll repeat my post:
using System.Windows.Forms.VisualStyles;
...
public Form1()
{
InitializeComponent();
if (Application.RenderWithVisualStyles)
{
VisualStyleRenderer rndr = new VisualStyleRenderer(VisualStyleElement.Button.GroupBox.Normal);
Color c = rndr.GetColor(ColorProperty.TextColor);
label1.ForeColor = c;
}
}
The label exposes a ForeColorChanged event. You can then do something like this:
this.label1.ForeColorChanged += (o,e) => { this.groupBox1.ForeColor = this.label1.ForeColor;};
If however you're trying to detect when the user changes their Theme, you can hook into the SystemEvents which can be found in the Microsoft.Win32 namespace. Something like this:
Microsoft.Win32.SystemEvents.UserPreferenceChanged += new Microsoft.Win32.UserPreferenceChangedEventHandler(SystemEvents_UserPreferenceChanged);
void SystemEvents_UserPreferenceChanged(object sender, Microsoft.Win32.UserPreferenceChangedEventArgs e)
{
this.groupBox1.ForeColor = this.label1.ForeColor;
}
I assume you use Windows Forms and not WPF. When you apply colors use the system colors (e.g. Control or HighlightText) these will be changed when the user switch the windows theme. Here is the code to set the color of the group box to system color and then apply this color for a label:
groupBox1.ForeColor = SystemColors.ActiveBorder;
label1.ForeColor = groupBox1.ForeColor;

Categories

Resources