Click here to Skip to main content
Licence CPOL
First Posted 16 Sep 2011
Views 11,436
Bookmarked 1 time

WinForms.ColorDialog in WPF

By | 7 Feb 2012 | Technical Blog
This article demostrates how to use System.Windows.Forms.ColorDialog in a WPF project. Why you may ask, simply because one can and must try… For not wanting to design a UserControl nor an extra project for my solution I started an extensive search for a simplistic solution and thus I created t
A Technical Blog article. View original blog here.[^]

This article demostrates how to use System.Windows.Forms.ColorDialog in a WPF project.
Why you may ask, simply because one can and must try…

For not wanting to design a UserControl nor an extra project for my solution I started an extensive search for a simplistic solution and thus I created the following. It also demostrates how to use Winform components in a WPF solution.

To demostrate I’ve made a small TextEditor. I’ll show how to change the foreground / background color of the selected text within a RichTextBox.

1) Create
Create a new solution with a WPF project named TextEditor

2) Add References:
System.Windows.Forms.dll and System.Drawing.dll
Both can be found in the folowing directory.:
” C:\Windows\Microsoft.NET\Framwork\v2.0.50727\ ”

3) Images
Add a folder to the project and name it Images, the add the images needed for the toolbar.

4) Document Manager
Add a class to the project and name it DocumentManager.cs, then add a few methods.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using Microsoft.Win32;

namespace TextEditor
{
  class DocumentManager
  {
    private string _currentFile;
    private RichTextBox _textBox;

    public DocumentManager(RichTextBox textBox)
    {
       _textBox = textBox;
    }

    public void ApplyToSelection(DependencyProperty property, object value)
    {
      _textBox.Selection.ApplyPropertyValue(property, value);
    }

    public bool OpenDocument()
    {
      OpenFileDialog dlg = new OpenFileDialog();
      if (dlg.ShowDialog() == true)
      {
        _currentFile = dlg.FileName;
        using (Stream stream = dlg.OpenFile())
        {
          TextRange range = new TextRange(
          _textBox.Document.ContentStart,
          _textBox.Document.ContentEnd);
          range.Load(stream, DataFormats.Rtf);
         }
         return true;
      }
      return false;
    }

    public bool SaveDocument()
    {
      if (string.IsNullOrEmpty(_currentFile)) return SaveDocumentAs();
      else
      {
         using (Stream stream =
                         new FileStream(_currentFile, FileMode.Create))
         {
           TextRange range = new TextRange(
           _textBox.Document.ContentStart,
           _textBox.Document.ContentEnd);
           range.Save(stream, DataFormats.Rtf);
          }
          return true;
      }
     }

    public bool SaveDocumentAs()
    {
      SaveFileDialog dlg = new SaveFileDialog();
      if (dlg.ShowDialog() == true)
      {
        _currentFile = dlg.FileName;
        return SaveDocument();
       }
       return false;
    }

    public void NewDocument()
    {
      _currentFile = null;
      _textBox.Document = new FlowDocument();
     }
  }
}

5) MainWindow.xml

<window x:Class="TextEditor.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525">
    <dockpanel>
        <toolbartray DockPanel.Dock="top">
            <toolbar>
                <button x:Name="highlight" Click="Highlight_Click">
                    <image Source="Images\text_highlight.png" />
                </button>
                <button x:Name="color" Click="Color_Click">
                    <image Source="Images\text_Color.png" />
                </button>
            </toolbar>
        </toolbartray>
        <richtextbox x:Name="body"
                     SelectionChanged="body_SelctionChanged"
                     SpellCheck.IsEnabled="True"
                     AcceptsReturn="True"
                     AcceptsTab="True"
                     BorderThickness="0 2 0 0" />
    </dockpanel>
</window>

6) MainWindow.xaml.cs

usisng System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TextEditor
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>

    public partial class MainWindow : Window
    {
        private DocumentManager _documentManager;
        public MainWindow()
        {
            InitializeComponent();

            // Insert code required on object creation below this point.
            _documentManager = new DocumentManager(body);
        }

        private void body_SelctionChanged(object seder, RoutedEventArgs e)
        {
            //update the tool bar
        }

        private void Highlight_Click(object sender, RoutedEventArgs e)
        {
            SolidColorBrush scb = new SolidColorBrush();
            _documentManager.ApplyToSelection(
                                  TextBlock.ForegroundProperty,
                                  new SolidColorBrush(colorPicker())
                                  );
        }
        private void Color_Click(object sender, RoutedEventArgs e)
        {
            _documentManager.ApplyToSelection(
                                  TextBlock.BackgroundProperty,
                                  new SolidColorBrush(colorPicker())
                                  );
        }

        private System.Windows.Media.Color colorPicker()
        {
            System.Windows.Forms.ColorDialog colorDialog =
                       new System.Windows.Forms.ColorDialog();
            colorDialog.AllowFullOpen = true;
            colorDialog.ShowDialog();

            System.Windows.Media.Color col =
                                   new System.Windows.Media.Color();
            col.A = colorDialog.Color.A;
            col.B = colorDialog.Color.B;
            col.G = colorDialog.Color.G;
            col.R = colorDialog.Color.R;
            return col;
        }
    }
}

Conclusion

I’ve learned that one doesn’t need to discard old libruarys.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

kribo

Software Developer

Belgium Belgium

Member

Follow on Twitter Follow on Twitter
Developer within C#, Dynamics NAV (Navision), Php environments.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionImprove... PinmemberVallarasuS22:17 7 Feb '12  
AnswerRe: Improve... Pinmemberkribo7:59 8 Feb '12  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 8 Feb 2012
Article Copyright 2011 by kribo
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid