Cannot implicitly convert type system windows point to system drawing point

cannot implicitly convert type int to system.drawing.size [closed]

This is giving me the error «cannot implicitly convert type int to system.drawing.size»

5 Answers 5

Size is a struct with two integer properties. You could do myNumericUpDown.MinimumSize = new Size(10,10); .

Size is defined as Width and Height , if you want to set MinimumSize you will have to declare a Size object and set the Width and Height

It’s pretty clear what the compiler is complaining about.

The property is of type System.Drawing.Size and you are trying to use an int .

myNumericUpDown.MinimumSize = new Size(2,4);

MinimumSize is a property that gets SIZE class.

But if you meant Minimum (Gets or sets the minimum allowed value for the spin box)

Size is a struct defined in System.Drawing

You cannot implicitly convert from Size to int .

You probably meant myNumbericUpDown.MinimumSize = new Size(1,1);

Not the answer you’re looking for? Browse other questions tagged c# c#-4.0 or ask your own question.

Hot Network Questions

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

How to correctly convert System.Drawing.Point to System.Windows.Point?

First, I didn’t find any answer so far. The article here on this site does not answer my question: Converter of System.Drawing.Point’ to ‘System.Windows.Point

In the above article, one suggests to convert like this:

But the conversion does not seem to get the correct result. I got the System.Drawing.Point from a click event of a WinForm that embeds WPF visual. When I try to identify the Control clicked in WPF visual using above conversion and VisualTreeHelper.HitTest(), the top-left Control can be identified correctly, the more to the right-bottom the more inaccurate. Means the point conversion is not a simple X-to-X and Y-to-Y copy. There must be some other factors involved. Any ideas, do we need consider other display factors in conversion? Please run the attached program and clicking on different point on the Grid, you will find out the strange behavior.

I have a WPF UI embedded in WinForm. When a HelpButton “?” on the WinForm is clicked followed by a click on a Control in the WPF UI, the WinForm get notified and I can get the correct System.Drawing.Point in the WinForm. Then I want to get the corresponding location clicked in the WPF. I calculated the relative System.Drawing.Point to the ElementHost which is the last WinForm element connecting the first WPF visual, then try to use above way to get System.Windows.Point inside WPF UI, but it does not get the correct point that is corresponding to the location clicked.

We have some third-party UI libraries as UserControls which cannot be changed. We use a WinForm to hold them. However we want to intrude the UserControls and add Help-Window when user clicks «?» button on the WinForm (then the mouse cursor changes to ?) and then click on an UI control in the UserControls. This works fine if third-party UI is written purely in WinForm.

What we did was that we first got the Point of click inside the WinForm by this: System.Drawing.Point pt = this.PointToClient(e.MousePos);

then got the front-most Control. Form.GetChildAtPoint(pt);

Then got the visual-tree path to that control by recursively climbing-up the visual-tree and record the Name property or Text property of each Control in the path: Control parent = child.Parent;

Then we use the path as a string to look up a predefined table to determine the keyword to identify that Control. Once the Control is identified by the keyword, the keyword can map to a Help-Window or its ToolTip.

The above procedure works fine if everything is WinForm.

However when the UserControl contains an ElementHost and embedded WPF content, the above is broken. I think as long as I can translate the “System.Drawing.Point” to “System.Windows.Point” correctly, then it should work as well.

The following code demonstrate the problem: Reproduction procedure:

Start the program.

Click on «?» button, cursor changes to «?».

Читайте также:  Windows форматировать флешку cmd

Click on one of the 3 buttons, a popup window gives the visual path.

Point Структура

Определение

Представляет упорядоченную пару целых чисел — координат Х и Y, определяющую точку на двумерной плоскости. Represents an ordered pair of integer x- and y-coordinates that defines a point in a two-dimensional plane.

Примеры

В следующем примере кода создаются точки и размеры с помощью нескольких перегруженных операторов, определенных для этих типов. The following code example creates points and sizes using several of the overloaded operators defined for these types. В нем также показано, как использовать SystemPens класс. It also demonstrates how to use the SystemPens class.

Этот пример предназначен для использования с Windows Forms. This example is designed to be used with Windows Forms. Создайте форму, содержащую Button имя subtractButton . Create a form that contains a Button named subtractButton . Вставьте код в форму и вызовите CreatePointsAndSizes метод из формы Paint метода обработки событий, передав его e как PaintEventArgs . Paste the code into the form and call the CreatePointsAndSizes method from the form’s Paint event-handling method, passing e as PaintEventArgs.

Комментарии

Чтобы преобразовать в Point PointF , используйте Implicit . To convert a Point to a PointF, use Implicit.

Конструкторы

Инициализирует новый экземпляр структуры Point, используя в качестве координат указанное целое значение. Initializes a new instance of the Point struct using coordinates specified by an integer value.

Инициализирует новый экземпляр структуры Point с указанными координатами. Initializes a new instance of the Point struct with the specified coordinates.

Инициализирует новый экземпляр структуры Point на основе Size. Initializes a new instance of the Point struct from a Size.

Представляет объект Point, у которого значения X и Y установлены равными нулю. Represents a Point that has X and Y values set to zero.

Свойства

Возвращает значение, указывающее, пуст ли массив Point. Gets a value indicating whether this Point is empty.

Возвращает или задает координату Х точки Point. Gets or sets the x-coordinate of this Point.

Возвращает или задает координату Y точки Point. Gets or sets the y-coordinate of this Point.

Методы

Добавляет заданный размер Size к точке Point. Adds the specified Size to the specified Point.

Преобразует указанную структуру PointF в структуру Point, округляя значения PointF до ближайшего большего целого числа. Converts the specified PointF to a Point by rounding the values of the PointF to the next higher integer values.

Определяет, содержит ли этот экземпляр точки те же координаты, что и указанный объект. Specifies whether this point instance contains the same coordinates as the specified object.

Определяет, содержит ли этот экземпляр точки те же координаты, что и другая точка. Specifies whether this point instance contains the same coordinates as another point.

Возвращает хэш-код для данного свойства Point. Returns a hash code for this Point.

Преобразует объект Point на заданную величину. Translates this Point by the specified amount.

Смещает точку Point на указанную точку Point. Translates this Point by the specified Point.

Преобразует указанный объект PointF в Point, округляя значения PointF до ближайших целых чисел. Converts the specified PointF to a Point object by rounding the PointF values to the nearest integer.

Возвращает результат вычитания заданного размера Size из заданной точки Point. Returns the result of subtracting specified Size from the specified Point.

Преобразует объект Point в строку, доступную для чтения. Converts this Point to a human-readable string.

Преобразует указанную точку PointF в точку Point путем усечения значений объекта PointF. Converts the specified PointF to a Point by truncating the values of the PointF.

Операторы

Смещает точку Point на заданное значение Size. Translates a Point by a given Size.

Сравнивает два объекта Point. Compares two Point objects. Результат определяет, равны значения свойств X и Y двух объектов Point или нет. The result specifies whether the values of the X and Y properties of the two Point objects are equal.

Преобразует указанную структуру Point в структуру Size. Converts the specified Point structure to a Size structure.

Преобразует указанную структуру Point в структуру PointF. Converts the specified Point structure to a PointF structure.

Сравнивает два объекта Point. Compares two Point objects. Результат показывает неравенство значений свойств X или Y двух объектов Point. The result specifies whether the values of the X or Y properties of the two Point objects are unequal.

Смещает Point на отрицательное значение, заданное параметром Size. Translates a Point by the negative of a given Size.

Point Converter Класс

Определение

Преобразует объект Point из одного типа данных в другой. Converts a Point object from one data type to another.

Примеры

В следующем примере кода показано, как использовать PointConverter Subtraction оператор и. The following code example demonstrates how to use the PointConverter and the Subtraction operator. Этот пример предназначен для использования с Windows Forms. This example is designed to be used with Windows Forms. Вставьте этот код в форму и вызовите ShowPointConverter метод при обработке Paint события формы, передав его e как PaintEventArgs . Paste this code into a form and call the ShowPointConverter method when handling the form’s Paint event, passing e as PaintEventArgs .

Читайте также:  Стратегия реального времени для windows 10

Комментарии

PointConverterКласс обычно используется для создания интерфейса времени разработки для элементов управления, имеющих свойства типа Point , и используется для преобразования точек в строки для вывода в конструктор и преобразования строк, введенных в конструктор, в Point объект. The PointConverter class is typically used for creating a design-time experience for controls that have properties that are of type Point, and is used to convert points to strings for display in a designer and to convert strings entered in a designer to a Point object. Доступ к данному классу осуществляется с помощью объекта TypeDescriptor. Access this class through the TypeDescriptor object.

Конструкторы

Инициализирует новый экземпляр класса PointConverter. Initializes a new instance of the PointConverter class.

Методы

Определяет, может ли данный преобразователь преобразовывать объект заданного типа источника в собственный тип преобразователя. Determines if this converter can convert an object in the given source type to the native type of the converter.

Возвращает значение, указывающее, может ли этот преобразователь преобразовать объект заданного типа к типу этого преобразователя. Returns whether this converter can convert an object of the given type to the type of this converter.

(Унаследовано от TypeConverter) CanConvertTo(ITypeDescriptorContext, Type)

Возвращает значение, указывающее, может ли данный преобразователь преобразовать объект с помощью контекста в заданный конечный тип. Gets a value indicating whether this converter can convert an object to the given destination type using the context.

Возвращает значение, указывающее, может ли этот преобразователь выполнить преобразование данного объекта к заданному типу. Returns whether this converter can convert the object to the specified type.

(Унаследовано от TypeConverter) ConvertFrom(ITypeDescriptorContext, CultureInfo, Object)

Преобразовывает указанный объект в объект Point. Converts the specified object to a Point object.

Приводит заданное значение к типу этого преобразователя. Converts the given value to the type of this converter.

(Унаследовано от TypeConverter) ConvertFromInvariantString(ITypeDescriptorContext, String)

Преобразует заданную строку к типу этого преобразователя, используя нейтральные язык и региональные параметры вместе с заданным контекстом. Converts the given string to the type of this converter, using the invariant culture and the specified context.

(Унаследовано от TypeConverter) ConvertFromInvariantString(String)

Преобразует заданную строку к типу этого преобразователя, используя нейтральные язык и региональные параметры. Converts the given string to the type of this converter, using the invariant culture.

(Унаследовано от TypeConverter) ConvertFromString(ITypeDescriptorContext, CultureInfo, String)

Преобразует заданный текст в объект, используя заданный контекст и сведения о языке и региональных параметрах. Converts the given text to an object, using the specified context and culture information.

(Унаследовано от TypeConverter) ConvertFromString(ITypeDescriptorContext, String)

Преобразует заданный текст в объект, используя заданный контекст. Converts the given text to an object, using the specified context.

(Унаследовано от TypeConverter) ConvertFromString(String)

Преобразует заданный текст в объект. Converts the specified text to an object.

(Унаследовано от TypeConverter) ConvertTo(ITypeDescriptorContext, CultureInfo, Object, Type)

Преобразует указанный объект в заданный тип. Converts the specified object to the specified type.

Преобразует данное значение в указанный тип, используя заданные аргументы. Converts the given value object to the specified type, using the arguments.

(Унаследовано от TypeConverter) ConvertToInvariantString(ITypeDescriptorContext, Object)

Преобразует указанное значение в строковое представление для нейтральных языка и региональных параметров. Converts the specified value to a culture-invariant string representation, using the specified context.

(Унаследовано от TypeConverter) ConvertToInvariantString(Object)

Преобразует указанное значение в строковое представление для нейтральных языка и региональных параметров. Converts the specified value to a culture-invariant string representation.

(Унаследовано от TypeConverter) ConvertToString(ITypeDescriptorContext, CultureInfo, Object)

Преобразует данное значение в заданный тип, используя заданный контекст и сведения о языке и региональных параметрах. Converts the given value to a string representation, using the specified context and culture information.

(Унаследовано от TypeConverter) ConvertToString(ITypeDescriptorContext, Object)

Преобразует данное значение в строку, используя данный контекст. Converts the given value to a string representation, using the given context.

(Унаследовано от TypeConverter) ConvertToString(Object)

Преобразует указанное значение в строковое представление. Converts the specified value to a string representation.

Читайте также:  Чем посмотреть исполняемый файл linux

(Унаследовано от TypeConverter) CreateInstance(IDictionary)

Повторно создает объект Object, задающий набор значений свойств для объекта. Re-creates an Object given a set of property values for the object.

(Унаследовано от TypeConverter) CreateInstance(ITypeDescriptorContext, IDictionary)

Создает экземпляр этого типа, задавая набор значений свойств для объекта. Creates an instance of this type given a set of property values for the object.

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) GetConvertFromException(Object)

Возвращает исключение, возникающее в случае, если невозможно выполнить преобразование. Returns an exception to throw when a conversion cannot be performed.

(Унаследовано от TypeConverter) GetConvertToException(Object, Type)

Возвращает исключение, возникающее в случае, если невозможно выполнить преобразование. Returns an exception to throw when a conversion cannot be performed.

(Унаследовано от TypeConverter) GetCreateInstanceSupported()

Возвращает значение, показывающее, требуется ли при изменении значения этого объекта вызывать метод CreateInstance(IDictionary), чтобы создать новое значение. Returns whether changing a value on this object requires a call to the CreateInstance(IDictionary) method to create a new value.

(Унаследовано от TypeConverter) GetCreateInstanceSupported(ITypeDescriptorContext)

Определяет, требуется ли вызов CreateInstance(ITypeDescriptorContext, IDictionary) для создания нового значения при изменении значения объекта. Determines if changing a value on this object should require a call to CreateInstance(ITypeDescriptorContext, IDictionary) to create a new value.

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetProperties(ITypeDescriptorContext, Object)

Возвращает коллекцию свойств для типа массива, заданного параметром, используя заданный контекст. Returns a collection of properties for the type of array specified by the value parameter, using the specified context.

(Унаследовано от TypeConverter) GetProperties(ITypeDescriptorContext, Object, Attribute[])

Извлекает набор свойств для данного типа. Retrieves the set of properties for this type. По умолчанию тип не возвращает свойства. By default, a type does not return any properties.

Возвращает коллекцию свойств для типа массива, заданного параметром значения. Returns a collection of properties for the type of array specified by the value parameter.

(Унаследовано от TypeConverter) GetPropertiesSupported()

Возвращает значение, показывающее, поддерживаются ли свойства этим объектом. Returns whether this object supports properties.

(Унаследовано от TypeConverter) GetPropertiesSupported(ITypeDescriptorContext)

Определяет, поддерживает ли объект свойства. Determines if this object supports properties. По умолчанию используется значение false . By default, this is false .

Возвращает коллекцию стандартных значений из контекста по умолчанию для типа данных, для которого предназначен этот преобразователь типов. Returns a collection of standard values from the default context for the data type this type converter is designed for.

(Унаследовано от TypeConverter) GetStandardValues(ITypeDescriptorContext)

Возвращает коллекцию стандартных значений для типа данных, для которого предназначен этот преобразователь типов при предоставлении с контекстом формата. Returns a collection of standard values for the data type this type converter is designed for when provided with a format context.

(Унаследовано от TypeConverter) GetStandardValuesExclusive()

Возвращает значение, показывающее, является ли исчерпывающим списком коллекция стандартных значений, возвращаемая методом GetStandardValues(). Returns whether the collection of standard values returned from GetStandardValues() is an exclusive list.

(Унаследовано от TypeConverter) GetStandardValuesExclusive(ITypeDescriptorContext)

Используя заданный контекст, возвращает значение, показывающее, является ли исчерпывающим списком возможных значений коллекция стандартных значений, возвращаемая методом GetStandardValues(). Returns whether the collection of standard values returned from GetStandardValues() is an exclusive list of possible values, using the specified context.

(Унаследовано от TypeConverter) GetStandardValuesSupported()

Возвращает значение, показывающее, поддерживает ли объект стандартный набор значений, которые можно выбрать из списка. Returns whether this object supports a standard set of values that can be picked from a list.

(Унаследовано от TypeConverter) GetStandardValuesSupported(ITypeDescriptorContext)

Получает значение, показывающее, поддерживает ли этот объект стандартный набор значений, которые можно выбрать из списка, используя заданную контекстную информацию. Returns whether this object supports a standard set of values that can be picked from a list, using the specified context.

(Унаследовано от TypeConverter) GetType()

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) IsValid(ITypeDescriptorContext, Object)

Возвращает значение, показывающее, допустим ли для этого типа и указанного контекста данный объект значения. Returns whether the given value object is valid for this type and for the specified context.

(Унаследовано от TypeConverter) IsValid(Object)

Возвращает значение, показывающее, допустим ли для этого типа данный объект значения. Returns whether the given value object is valid for this type.

(Унаследовано от TypeConverter) MemberwiseClone()

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) SortProperties(PropertyDescriptorCollection, String[])

Сортирует коллекцию свойств. Sorts a collection of properties.

(Унаследовано от TypeConverter) ToString()

Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.

Оцените статью