Click here to Skip to main content
15,893,722 members
Articles / Desktop Programming / WPF

WinForms.ColorDialog in WPF

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
7 Feb 2012CPOL 21.9K   1   2
How to use System.Windows.Forms.ColorDialog in a WPF project

This article demonstrates 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 demonstrates how to use Winform components in a WPF solution.

To demonstrate, 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 following directory:

  • ” C:\Windows\Microsoft.NET\Framework\v2.0.50727\ ”

3) Images

Add a folder to the project and name it Images, then 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:

C#
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

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

C#
using 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 libraries.

This article was originally posted at http://blog.kribo.be/blog?p=243

License

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


Written By
Web Developer
Belgium Belgium
Developer within C#, Dynamics NAV (Navision), Php environments.

Comments and Discussions

 
QuestionImprove... Pin
VallarasuS7-Feb-12 22:17
VallarasuS7-Feb-12 22:17 
AnswerRe: Improve... Pin
kribo8-Feb-12 7:59
professionalkribo8-Feb-12 7:59 

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

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