could you fix me with my problem?
I have got a text field in my Form. And I would like to print Date and Time in a string,I mean, where cursor is.
I got this class for this:
#include <Windows.h>
//Russian letters are okay for this
private: System::Void времяИДатаToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
SYSTEMTIME sys_t;
GetSystemTime(&sys_t);
char szFormat[] = "MMMM";
char Buffer[16];
sys_t.wMonth = 1;
GetDateFormat(LOCALE_USER_DEFAULT, 0, &sys_t, szFormat, Buffer, 256);
}
};
I would like to use MessageBox::Show() , but it isn't for my problem?
Can you give some advice for this?
Thanks.
Standard warning: While it's certainly possible to write the main body of your application in C++/CLI, or even write the GUI in C++/CLI using WinForms, it is not recommended. C++/CLI is intended for interop scenarios: where C# or other .Net code needs to interface with unmanaged C++, C++/CLI can provide the translation between the two. For primary development, it is recommended to use C# with either WinForms or WPF if you want managed code, or C++ with MFC if you want unmanaged.
OK, that said: You've got the full .Net library available to you, why not use it?
void времяИДатаToolStripMenuItem_Click(Object^ sender, EventArgs^ e)
{
DateTime now = DateTime::Now;
String^ dateString = now.ToString("MMMM");
}
Assuming your text field is called textField, use:
textField->Text = new string(Buffer);
Also, your call to
GetDateFormat(LOCALE_USER_DEFAULT, 0, &sys_t, szFormat, Buffer, 256);
Is wrong. Pass 16, not 256 as the last argument (because you declared Buffer to have 16 chars).
Related
I sank most of last night looking into this and found lots of half answers that didn't quite work for my fairly common issue.
I have a Textbox that i want to save to an Integer in a Database. I need to only allow the user to enter valid integers with no spaces so that:
-14 valid
14 valid
0 valid
invalid
14.3 invalid
1-4 invalid
A14 invalid
14A invalid
"14 " (has whitespace) invalid
14 (has whitespace) invalid
1 4 (has whitespace) invalid
you get the picture. only integers.
form what iv'e found this method is the key. but I cant figure out/find the regex/alternative to validate it correctly
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
//Validation code here
}
There's no need to reinvent the wheel.
Use a control such as IntegerUpDown from the Extended WPF Toolkit
I've been using MVVM so after working through a bunch of the answers in the sugested "Sugested Answer"
the Approved answer didn't validate it correctly. and all the Regex examples failed to account for the order of the - when dealing with negatives.
But using MVVM you can make the binding "Mode=TwoWay and UpdateSourceTrigger=PropertyChanged" then it validates it's self.
wont work if you don't want two way binding, so the ideal regex solution is still to be solved.
but this solves my issue.
I use regex for this : private static readonly Regex _regex = new Regex("[^0-9]");
you can bool property for it private static bool IsTextAllowed(string text)
{
return !_regex.IsMatch(text);
}
and then call it private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsTextAllowed(e.Text);
}
I have followed the monogame wpf sample and the old XNA wpf sample to create a view in WPF with a loaded model through monogame (I'm also using mvvmlight but that shouldn't matter much I hope).
Everything else works except the contentManager I.e. Making a cube out of vertices is displayed fine with a local instance of GraphicsDevice
Depending on whether I use IntPtr.Zero or the actual window handle to create the instance of GraphicsDevice I get a different error and neither give many details so I don't know which I should persue...
When I use IntPtr.Zero
_services = new ServiceContainer();
_services.AddService(typeof(IGraphicsDeviceService), _graphicsDeviceService);
ContentManager content = new ContentManager(_services, "");
var model = content.Load<Model3D>("psp"); // At this line
I get an error about
"The type initializer for 'Microsoft.Xna.Framework.TitleContainer' threw an exception."
Inner Exception: The process has no package identity. (Exception from HRESULT: 0x80073D54)
But when I use the Actual WindowPointer I get this error
Managed Debugging Assistant 'FatalExecutionEngineError' has detected a problem in 'E:\Documents\Visual Studio 2013\Projects\XSITE2DEV\xSite2Dev\MvvmMonogameTest\bin\Debug\MvvmMonogameTest.vshost.exe'.
Additional information: The runtime has encountered a fatal error. The address of the error was at 0x71985144, on thread 0x5f38. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
In the GraphicsDeviceService creating the first instance of GraphicsDevice
I get my window pointer by using these methods
/// <summary>
/// Gets a reference to the singleton instance.
/// </summary>
public static GraphicsDeviceService AddRef(int width, int height)
{
var singletonInstance = SimpleIoc.Default.GetService(typeof(IGraphicsDeviceService)) as GraphicsDeviceService;
// Increment the "how many controls sharing the device" reference count.
if (Interlocked.Increment(ref _referenceCount) == 1)
{
// If this is the first control to start using the
// device, we must create the device.
singletonInstance.EnsureGraphicsDevice();
}
return singletonInstance;
}
private void EnsureGraphicsDevice()
{
if (_graphicsDevice != null)
return;
//CreateDevice(IntPtr.Zero, 1, 1);
CreateDevice(new WindowInteropHelper(Application.Current.MainWindow).Handle, 1, 1);
}
private void CreateDevice(IntPtr windowHandle, int width, int height)
{
_parameters = new PresentationParameters
{
BackBufferWidth = Math.Max(width, 1),
BackBufferHeight = Math.Max(height, 1),
BackBufferFormat = SurfaceFormat.Color,
DepthStencilFormat = DepthFormat.Depth24,
DeviceWindowHandle = windowHandle,
PresentationInterval = PresentInterval.Immediate,
IsFullScreen = false
};
_graphicsDevice = new GraphicsDevice(
GraphicsAdapter.DefaultAdapter,
GraphicsProfile.HiDef,
_parameters);
if (DeviceCreated != null)
DeviceCreated(this, EventArgs.Empty);
}
I feel like using the actual window pointer is the correct approach but the error has no further details so I can't go anywhere with it..
I came across a similar error while using an implementation as yours. For me, it occured because Game.Instance was null and if you look up the source code of GraphicsDevice at the MonoGame source, you will find that the constructor depends on that (at least in OpenGL).This link could be helpful:
https://github.com/mono/MonoGame/issues/2586
Basically, you have two options:
Bringing a Game in (e.g. inheriting from Game) will set Game.Instance in the constructor
Customizing the MonoGame Source to use your Handle
By the way I am not 100% sure that this is what is causing your error message.
I know that this post is old and I am quite likely too late but this may be helpful for anybody else who is experiencing this error.
I am using Visual C++ 2010 Express. I have a form (Form1.h) that contains a button (btn1) and a label (label1).
When I click the button, I would like to call a function from a different header file (testing.h) that will then proceed to change the text in the label.
What I have is something like this...
Form1.h
#include "testing.h"
... standard form code generated by Visual Studio
private: System::Windows::Forms::Label^ label1;
...
private: System::Void btn1_Click(System::Object^ sender, System::EventArgs^ e) {
testfunc1();
}
};
Where testing.h is something like...
#ifndef _TESTING_FUNCS
#define _TESTING_FUNCS
void testfunc1(){
label1->Text = "Text has been changed from outside.";
}
#endif
When I try to compile and run it, I get errors saying that 'label1' is an undeclared identifier (within testing.h), and an error referring to the "left of '->Text' must point to class/struct/..."
I am new to C++ and usually use Java, so there are a few new things for me here. To me, there are two obvious options:
1) Pass the label to the function as an argument
2) Somehow access the label from the testing.h header file, sans reference
But I'm not really sure how to do either.
The label is a private variable of a class and just like in Java is not accessible from the outside, especially not in static context. You can pass the label, or you can create an accessor function in your Form and pass the whole form.
Example for passing the label:
void testfunc1(System::Windows::Forms::Label^ someLabel)
{
someLabel->Text = "Text has been changed from outside.";
}
Calling it:
System::Void btn1_Click(System::Object^ sender, System::EventArgs^ e)
{
testfunc1(label1);
}
In my C# winforms application, I am using the Graphics object to obtain the current DPI value to enable my code to scale certain components. This works fine except that, as soon as I call CreateGraphics(), the look and feel of my winforms application changes. The style goes from the familiar "rounded" buttons to the more archaic looking "sharp edged" buttons.
Why is this happening and what can I do to prevent it?
My code looks like the following:
Graphics g = this.CreateGraphics();
try
{
if (g.DpiX == 120.0f)
{
// scale the components appropriately
}
}
finally
{
g.Dispose();
}
In fact I can reproduce the problem just by calling CreateGraphics and then instantly disposing of it.
Any help or insight much appreciated!
And alternative question is: is there anyway to obtain the DPI setting without creating a Graphics object?
I was working on the DPI problem some time ago, when a colleague started working with a high-DPI display.
My apporach was to ask the Desktop, not a specific window for the Dpi. As I run into some troubles, I came up with this code (not pretty, but worked for me quite well):
/// <summary>
/// Assesses the Systems Primary Monitor's DPI value
/// </summary>
public static double DPI {
get {
Graphics g = Graphics.FromHwnd(IntPtr.Zero);
IntPtr desktop = g.GetHdc();
int LogicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.VERTRES);
int PhysicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.DESKTOPVERTRES);
float ScreenScalingFactor = (float)PhysicalScreenHeight / (float)LogicalScreenHeight;
// dpi1 answers correctly if application is "dpiaware=false"
int dpi1 = (int)(96.0 * ScreenScalingFactor);
// dpi2 answers correctly if application is "dpiaware=true"
int dpi2 = GetDeviceCaps(desktop, (int)DeviceCap.LOGPIXELSX);
return Math.Max(dpi1, dpi2);
}
}
[DllImport("gdi32.dll")]
static private extern int GetDeviceCaps(IntPtr hdc, int nIndex);
private enum DeviceCap {
VERTRES = 10,
DESKTOPVERTRES = 117,
LOGPIXELSX = 88,
// http://pinvoke.net/default.aspx/gdi32/GetDeviceCaps.html
}
I especially don't like the hack using the Math.Max(dpi1, dpi2), but for now I found no better solution.
As for your original Question, on Win10 I see no change in visuals. Sorry, no idea here.
I want to have an array of SerialPort-Objects for each Port in the System.
My idea was to make it in that way:
public ref class CommunicatorClass
{
private:
static array<SerialPort^>^ _serialPortList;
public:
static void Main(){
// _serialPortList->Initialize;
for each (String^ s in SerialPort::GetPortNames())
{
Console::WriteLine(" {0}", s);
AddListItem(s);
}
}
static void AddListItem(String^ s)
{
// Get the length
_serialPortList->Length = _serialPortList->GetLength + 1;
_serialPortList[_serialPortList->GetLength] = gcnew SerialPort(s, 9600);
}
};
but I am completely new to C++/Windows-Programming. So, yes, sure, there are many errors in. Can anyone please correct it (if the idea itself is not complete bullshit) and tell me some words on the errors ?
Would be nice, thank you in advance.
You want to actually open every serial port on the system, all at the same baud rate?
You can't change the length of an array, you have to create a brand-new one and copy over all the data, and it's inefficient to do that every time you need to add another item. I suggest using System::Collections::Generic::List instead, which takes care of all the dynamic resizing for you.
C++/CLI can call the native Windows serial port functions directly, and I suggest you do so, because the .NET SerialPort class is a piece of total garbage which forces you into a programming style that causes nothing but trouble. Of course you'll want to hide the Windows interface behind a wrapper class of your own, but it's well worth the effort.