Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
A

Alan N

@Alan N
About
Posts
490
Topics
5
Shares
0
Groups
0
Followers
0
Following
0

Posts

Recent Best Controversial

  • Is there a way to Convert binding dataMember?
    A Alan N

    Yes you just need to use a Format event handler on the Binding object For example

    private void AddBinding() {
      // Enable formatting and add the event handler
      Binding b = color1.DataBindings.Add("BackColor", NavBill.DataSource, "Color1", true);
      b.Format += PanelBackColorBinding\_Format;
    }
    
    private void PanelBackColorBinding\_Format(Object sender, ConvertEventArgs e) {
      if (e.DesiredType == typeof(Color)) {
        // Get the integer value from the DataColumn
        Int32 number = (Int32)e.Value;
        // Get the Color corresponding to the number
        // \*\*\* PUT YOUR OWN CODE HERE \*\*\*
        Color col = GetColor(number);
    
        // Assign the correct Color back into e.Value
        e.Value = col;
      }
    }
    

    Make sure that a default color is assigned to e.Value if there is any chance that the column will have missing or non convertable values.

    C# wpf wcf question

  • .NET 4.7 Desktop Form combox coloring within datagridview
    A Alan N

    Microsoft have knobbled many features of quite a few controls (e.g. ProgressBar - we all prefer green! MonthCalendar - change the font to make it big enough to see - No!) and often the only thing you can do is to disable visual styles. That can be a problem though as some controls require visual styles to be on (e.g the Tile mode of the ListView). However with the DataGridView the colour works in the way you desire when the FlatStyle of the ComboBoxColumn is set to either FlatStyle.Flat or FlatStyle.Popup. I guess they missed that.

    C# csharp

  • Downloading & Executing an Installer - User Cancels
    A Alan N

    Win32Exception has a NativeErrorCode property which should return 1223 (0x4C7) when the user stops a process starting at a UAC prompt. An example from my own code where I do something similar is probably clearer than more words!

    private static void RestartWithRunAs(ProcessStartInfo psi) {
      psi.UseShellExecute = true;
      psi.ErrorDialog = true;
      psi.Verb = "runas";
      try {
        Process.Start(psi);
      } catch (System.ComponentModel.Win32Exception exc) {
        // Accept cancelled by user as a valid action
        const Int32 CancelledByUser = 1223;
        if (exc.NativeErrorCode != CancelledByUser) {
          // MessageBox.Show(exc.ToString(), "Restart failure");
          throw;
        }
      }
    }
    

    See also System Error Codes (1000-1299) (WinError.h) - Win32 apps | Microsoft Learn[^] Alan.

    C# help question announcement

  • Strange behavior readline
    A Alan N

    Sub ClearKBBuffer()
    While Console.KeyAvailable
    Console.ReadKey(True)
    Console.ReadKey()
    End While
    End Sub

    Surely that will block when there are an odd numbers of keys in the input queue. Did you mean this

    Sub ClearKBBuffer()
    While Console.KeyAvailable
    Console.ReadKey(True)
    End While
    End Sub

    Alan.

    Visual Basic tutorial question

  • Get the value from a checklistbox
    A Alan N

    There is some confusion here as selection and checking are quite separate things and a selected item need not be checked. There is a SelectedValue property but there is no CheckedValue property. I'll assume that the checkedlistbox item collection stores instances of a class such as

    class NameID {
    public String Name {get; set;};
    public Int32 ID {get; set;}
    }

    To iterate though the ID's of the checkeditems do something like this

    for (int i = 0; i <= chkListClienteEmail.CheckedItems.Count - 1; i++)
    {

    Object rawObj = chkListClienteEmail.CheckedItems[i];
    NameID typedObj = (NameID)rawObj;

    string s = typedObj.ID.ToString();

    more code...
    }

    C#

  • A Hex on your Desktop
    A Alan N

    Thanks for the reply. I went away and reset the default app for the Photo viewer category to the MS recommended Photos app and the 15 file limit went away. Is that what you are using? Also Windows 10 Home may not be helping. On switching back to my own viewer the problem reappears as it does if I select MS Paint, Paint.NET, VLC Media Player, Firefox or Visual Studio 2017 as the viewer. All of which leaves me the Aaaargh state. So much so I may need to adulterate my afternoon coffee with whisky.

    The Lounge

  • A Hex on your Desktop
    A Alan N

    I was very pleased with myself today as I've been modifying my image viewer with single instance behaviour. Image filenames selected in Windows10 Explorer are forwarded to the first viewer process when the Enter key is pressed. It worked very well until one test when an image somehow got displayed as the desktop background. There is nothing in my code that could have done that and was surprised to discover some bizarre 'why oh why oh why' windows magic. When 1 to 15 image files are selected the action of the enter key is to open each file with the associated program (my viewer). If you dare to select 16 or more Microsoft have decided that what you want is a desktop image slide show. And to make sure you get the message they remove the 'Open' option from the context menu. Aaaaargh!

    The Lounge

  • Disable focus in button with arrow right left up down
    A Alan N

    Some of this key handling stuff is not obvious and I'm no expert! In this case you have to tell the Button control not to give the arrow keys special handling. To do this override the IsInputKey method. My example also overrides OnKeyDown to make buttons of this class move in response to the arrow keys. I imagine that you would want to have that functionality in a separate KeyDown event handler.

    public class AnnoyingButton : Button {

    protected override bool IsInputKey(Keys keyData) {
    return keyData == Keys.Up || keyData == Keys.Down ||
    keyData == Keys.Left || keyData == Keys.Right;
    }

    protected override void OnKeyDown(KeyEventArgs args) {
    Point newLocation = Location;

    switch (args.KeyCode) {
      case Keys.Right:
        newLocation.Offset(1, 0);
        Location = newLocation;
        break;
      case Keys.Left:
        newLocation.Offset(-1, 0);
        Location = newLocation;
        break;
      case Keys.Down:
        newLocation.Offset(0, 1);
        Location = newLocation;
        break;
      case Keys.Up:
        newLocation.Offset(0, -1);
        Location = newLocation;
        break;
      default:
        base.OnKeyDown(args);
    }
    

    }
    }

    I did have a good link about this stuff but as I'm moving computer I don't know where it is at the moment. EDIT: HERE IS THAT LINK Exploring Secrets of .NET Keystroke Handling[^] Alan.

    C# help

  • MaskedTextBox Focus ?
    A Alan N

    I think you are asking how to move the textbox caret to position 0 when the empty textbox is clicked. The first part is to get the empty state of the maskedtextbox before any data has been entered. At that point the Text property value is not String.Empty but a representation of the mask. This 'empty' text can be obtained by capturing the Text when the MaskChanged event fires. For your example it is

    "( ) "

    The second part is picking a suitable place to move the caret. When an unfocussed textbox is clicked the sequence of Enter, GotFocus and Click events occur. You'll find that attempting to set the caret position in either the Enter or GotFocus events will fail and changes must be made in the Click event handler. Combining that information gives some prototype code

    private String emptyText;

    private void MaskedTextBox_MaskChanged(object sender, EventArgs e) {
    // Capture the empty text
    MaskedTextBox mtbx = (MaskedTextBox)sender;
    emptyText = mtbx.Text;
    }

    private void MaskedTextBox_Click(object sender, EventArgs e) {
    MaskedTextBox mtbx = (MaskedTextBox)sender;
    String currentText = mtbx.Text;
    if (currentText == emptyText) {
    // Move the caret to the start of the line
    mtbx.Select(0, 0);
    }
    }

    EDIT : Correct operation of this code requires that the MaskChanged event handler is attached before the Mask is set. Alan.

    C# question

  • Efficiently sort the following?
    A Alan N

    The problem you have is that the desired arrangement within the 3 columns has no discernable order. You are grouping terms, City, California, Water, Breakfast etc, but the order of the groups seems completely random. For example why is the order of the states Florida, Texas, California? There is nothing about the strings which would suggest that order so there must be some other factor which is not in the data that you have shown. Alan.

    Algorithms csharp algorithms question

  • Efficiently sort the following?
    A Alan N

    Let's do this the old way! Sorting on multiple keys with a comparer method is straightforward (and easy to understand?). It is just a nested set of comparisons, compare the first key, if equal compare the second key, etc. For example let's say we have a list of strings and we want a custom sort. 1) by string length 2) alphabetically within each group of equal length The comparer method is

    private static Int32 SortByLengthThenAlpha(String x, String y) {
    // 1st sort
    Int32 result = x.Length.CompareTo(y.Length);
    // result will be < 0, 0, > 0

    if (result == 0) {
    // 2nd Sort, standard string sort
    result = x.CompareTo(y);

    // and so on if more is needed
    // if (result==0) {
    // }
    //
    

    }
    return result;
    }

    With an array of strings we can perform the sort with

    Array.Sort(strings, SortByLengthThenAlpha);

    Original Order

    Reddish
    Yellowish
    Redder
    Greenish
    Red
    Orange
    Yellow
    Orangy
    Green

    Sorted

    Red
    Green
    Orange
    Orangy
    Redder
    Yellow
    Reddish
    Greenish
    Yellowish

    Hope that helps explain the general idea. In your case the keys are the numeric values of T, H and L. Alan.

    Algorithms csharp algorithms question

  • Error in Panel AutoScroll after rotating a Picturebox within that Panel in VB.Net
    A Alan N

    The PictureBox is not perfect and if you turn on the borders you should be able to see that it does not resize itself correctly after the image has been rotated. In theory PictureBox.Refresh() or PictureBox.Invalidate() should sort out any problems but in my experience those methods do not help and the picturebox does not seem to know that the image has rotated. What I found helpful was to simply reassign the rotated image to the PictureBox.Image property. The strange alternate click issue with the Panel's scrollbars tends to happen if you muck about with the scroll properties. I came to the conclusion that Microsoft never meant us to change them! Alan.

    .NET (Core and Framework) help csharp

  • Writing to UI Thread in a Real time Application
    A Alan N

    The BackgroundWorker (BGW) uses a WindowFormsSynchronizationContext (SC) to invoke the completed and progress events on the UI thread. The SC comes from the thread that calls the RunWorkerAsync method. A non UI thread typically has no SC and then the BGW operates what is sometimes called the "free threaded model" using a ThreadPool thread to fire the completed and progress events. A BGW started from a new thread will behave properly if the thread is given the UI thread's SC. Some example code, I hope the missing bits are obvious.

    private void StartFromThreadWithContext_Click(Object sender, EventArgs e) {
    log.WriteLine("UI thread {0}", Thread.CurrentThread.ManagedThreadId);
    Thread starterThread = new Thread(StarterThreadProc);
    starterThread.Start(SynchronizationContext.Current);
    }

    private void StarterThreadProc(Object context) {
    log.WriteLine("Starting BGW from thread {0}", Thread.CurrentThread.ManagedThreadId);
    WindowsFormsSynchronizationContext wfsc = context as WindowsFormsSynchronizationContext;
    if (wfsc != null) {
    SynchronizationContext.SetSynchronizationContext(wfsc); // THE IMPORTANT BIT!!
    }
    log.WriteLine("Thread has {0}", SynchronizationContext.Current);
    worker.RunWorkerAsync();
    }

    private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
    log.WriteLine("RunWorkerCompleted thread {0}", Thread.CurrentThread.ManagedThreadId);
    }

    private void Worker_DoWork(object sender, DoWorkEventArgs e) {
    log.WriteLine("DoWork thread {0}", Thread.CurrentThread.ManagedThreadId);
    Thread.Sleep(300);
    }

    Output to the log shows correct invocation of the completed event

    UI thread 10
    Starting BGW from thread 12
    Thread has System.Windows.Forms.WindowsFormsSynchronizationContext
    DoWork thread 7
    RunWorkerCompleted thread 10

    Alan.

    C# csharp winforms linq graphics design

  • referencing a dll available in a different folder from a Windows Service without copying the dll
    A Alan N

    You can specify the location of strongly named assemblies in an application configuration file. I think doing so creates a maintenance nightmare but if you want to try it here are the details. Add a application configuration file to the project and add the following

    The location of the assembly is hard coded which is less than ideal and a slight improvement is possible by specifying a relative path in the codeBase href attribute. If application base directory is D:\MetraTech\RMP\BIN then this should be correct.

    If the ClientProxies.dll relies upon other assemblies within ..\Extensions\Account\Bin then a dependentAssembly element must be added for each one otherwise the assembly loader will only look in the GAC or the application base directory. Good luck and remember that all the xml is case sensitive. If you enter PublicKeyToken instead of publicKeyToken then the loader won't complain and will just quietly ignore the whole dependentAssembly element. Alan.

    C# csharp json help tutorial question

  • LocationChanged to set windowstate=Maximized
    A Alan N

    I think the ResizeBegin and ResizeEnd events will help you. The naming is misleading as the purpose of these events is to indicate when the form is showing the resizing border. Click and hold on the form border or caption bar and the ResizeBegin event is raised. ResizeEnd is seen on release whether or not any resizing has occurred. Here is a trivial (and annoying) modification to a form to make it maximise when it is moved without having changed it's size.

    private Rectangle? lastBounds;
    
    protected override void OnResizeBegin(EventArgs e) {
      base.OnResizeBegin(e);
      System.Diagnostics.Debug.Print("EVENT ResizeBegin");
      lastBounds = Bounds;
    }
    
    protected override void OnResizeEnd(EventArgs e) {
      base.OnResizeBegin(e);
      System.Diagnostics.Debug.Print("EVENT ResizeEnd");
      if (lastBounds.HasValue) {
        Rectangle previous = lastBounds.Value;
        // Maximise when moved without resizing
        if (previous != Bounds && previous.Size == Bounds.Size) {
          WindowState = FormWindowState.Maximized;
        }
        lastBounds = null;
      }
    }
    

    In your case it would be necessary to detect the System.Windows.Forms.Screen containing the form in ResizeBegin and test for the desired destination Screen in ResizeEnd. Alan.

    C# question

  • Docking and Anchoring
    A Alan N

    Control docking and anchoring are well understood by everybody and we all know that the two techniques are mutally exclusive. The help pages says something like "Only one can be set at a time, and the last one set takes precedence". I've always believed what I'm told by my elders and betters and was certain that code like the following would create an anchored control.

    FancyControl fc = new FancyControl();
    fc.Anchor = AnchorStyles.Top | AnchorStyles.Left;
    SomePanel.Controls.Add(fc);

    My FancyControl would typically be used fully docked and the constructor helpfully presets that condition. On the very rare occasion it should be anchored then just assign a value as shown. Why oh why then, did the control remained dicked?

    FancyControl fc = new FancyControl();
    Debug.Print("Dock: {0} Anchor: {1}", fc.Dock, fc.Anchor);
    // Dock: Fill Anchor: Top, Left
    fc.Anchor = AnchorStyles.Top | AnchorStyles.Left;
    SomePanel.Controls.Add(fc);

    On reading the Anchor property all became clear as the value was already Top|Left. Perhaps the Anchor property ignores redundant assignments? Of course it does and a delve into the published reference source confirms this. Search for DefaultLayout.SetAnchor in Reference Source[^] if you are interested. The final solution for the simple task of setting the control's anchor property is

    FancyControl fc = new FancyControl();
    fc.Dock = DockStyle.None;
    SomePanel.Controls.Add(fc);

    OK I should have included the statement fc.Anchor = AnchorStyles.Top | AnchorStyles.Left; after undocking but it's redundant! AlanN aka Alan "2f hours debugging" N

    The Weird and The Wonderful com debugging help question learning

  • strategy for run-time de-referencing of generic parameter ?
    A Alan N

    I'm not sure I understand the reason for the complexity. The final code fragment shows the use of the 'as' operator to perform a cast, implying that the type is known at compile time. If in fact all types are known then why use reflection at all, just go with is or as.

    public void CastingCouch() {
    List<ISomeInterface> someInstances = new List<ISomeInterface>();
    someInstances.Add(new SomeClass<int>(100, 200));
    someInstances.Add(new SomeClass<string>(200, "whoop de doo"));
    someInstances.Add(new SomeClass<DateTime>(300, DateTime.Now));

    foreach (ISomeInterface reference in someInstances) {
    Console.Write("{0} ", reference.GetType());

    if (reference is SomeClass<string>) {
      Console.WriteLine("String");
    } else if (reference is SomeClass<int>) {
      Console.WriteLine("Int");
    } else {
      Console.WriteLine("Don't know");
    }
    

    }
    }

    Alan.

    C# wpf wcf tutorial question discussion

  • Advice on Debugging Technique Needed
    A Alan N

    A .NET application may be executed within a separate AppDomain of an existing process and the application will use the culture associated with the thread. This may allow you to run your tool "X" without editing the registry. At it's simplest it just this: (compile as a Windows Application)

    using System;
    using System.Globalization;
    using System.Threading;

    namespace SpoofCulture {
    internal sealed class App2 {
    // Your apps full path here
    private const String TrialApp = @"E:\VC\Projects\AppDomainExec\Apps\TestApp.exe";
    // Your desired culture here
    private const String AppCulture = "fr-FR";
    //private const String AppCulture = "de-DE";

    \[STAThread\]
    private static void Main() {
      // Change the culture
      Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(AppCulture);
      AppDomain newDomain = AppDomain.CreateDomain("HostingDomain");
      newDomain.ExecuteAssembly(TrialApp);
      AppDomain.Unload(newDomain);
    }
    

    }
    }

    My TestApp.exe displays some culture dependent text, DateTime.Now.ToLongDateString() e.g.

    mercredi 23 mars 2016 when culture is fr-FR
    Mittwoch, 23. März 2016 de-DE

    Alan.

    Visual Studio tutorial debugging question

  • does MethodInvoker will not work on win XP?
    A Alan N

    mi.BeginInvoke(null, null) executes your PrintSomething() method asynchronously on a threadpool thread. Is that what you intended or did you mean to use Control.BeginInvoke(mi) to execute PrintSomething on the UI thread?

    C# performance question

  • Dragging A Control - Limits
    A Alan N

    I'm less at sub-novice level with WPF but I would imagine that the general principles for solving this problem will much the same as with System.Windows.Forms. Rather than attempting to calculate if an arbitrary new position is valid we can simply limit the mouse movement so that all achievable positions become ok. 1) On mouse button down calculate and set a constraining rectangle for the cursor 2) In mouse move relocate the label based on an offset from the cursor position 3) On losing mouse capture remove the constraining reactangle Here's one I prepared earlier. It should compile and run:

    using System;
    using System.Drawing;
    using System.Windows.Forms;

    namespace MouseMoveLabelDemo {
    public sealed class DemoForm : Form {
    [STAThread]
    private static void Main() {
    Application.Run(new DemoForm());
    }

    private readonly Point home;
    private Label itinerantLabel;
    private Size offset;
    
    public DemoForm() {
      home = new Point(10, 10);
      BackColor = Color.White;
    
      itinerantLabel = new Label();
      itinerantLabel.Text = "Move Me";
      itinerantLabel.BackColor = Color.Pink;
      itinerantLabel.BorderStyle = BorderStyle.FixedSingle;
      itinerantLabel.Location = home;
      itinerantLabel.Parent = this;
      itinerantLabel.MouseDown += Label\_MouseDown;
      itinerantLabel.MouseMove += Label\_MouseMove;
      itinerantLabel.MouseCaptureChanged += Label\_CaptureLost;
    
      SizeChanged += DemoForm\_SizeChanged;
    }
    
    private void DemoForm\_SizeChanged(object sender, EventArgs e) {
      // In this simple demo we don't want to lose the label 
      // so just send it home whenever the form is resized
      itinerantLabel.Location = home;
    }
    
    private void Label\_MouseDown(object sender, MouseEventArgs e) {
      Label lbl = (Label)sender;
      if (e.Button == MouseButtons.Left) {
        // Mouse is automatically captured on mouse down
    
        // All manipulations in Screen coordinates
        Point cursorPosition = Cursor.Position;
        Point labelPosition = PointToScreen(lbl.Location);
    
        // calculate offset of cursor from label origin
        offset = new Size(cursorPosition.X - labelPosition.X, cursorPosition.Y - labelPosition.Y);
    
        // Constrain cursor within a part of the ClientRectangle
        // (x1, y1) - (x2, y2)
        Rectangle cursorClippingRectangle = Rectangle.FromLTRB(
          // x1
          offset.Width,
          // y1
          offset.Height,
    
    C# question csharp wpf help
  • Login

  • Don't have an account? Register

  • Login or register to search.
  • First post
    Last post
0
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups