|
AFAIK there is no way unless the fields of your reference type field are also readonly. See this[^] at msdn.
|
|
|
|
|
Hi,
you can't in general. Some objects may have provisions for turning themselves into some kind of read-only state, e.g. a generic list can be declared read-only meaning you can't modify the list, but then you still can modify the list items themselves.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
Proxy it:
Return a interface which only provides readonly access.
You create the real object and the you create a proxy using the interface which encapsulates the real object.
|
|
|
|
|
A very interesting thought. I'm going to have to try this and see if it is practical.
I wasn't, now I am, then I won't be anymore.
|
|
|
|
|
I think this is the way I'm going to have to do it as some of the members can't be initialized via the constructor. I need to assign a couple later on in the process so "friend" would have been nice (NOTE: "internal" does not allow specifics and putting a few of these classes in another assembly is overkill for my small projects).
Later on I need to let other classes access these objects so that is where I'd love to mark a const intention. I guess I'll pass back the interface to achieve this.
I'm really surprised C# does not implement such useful idea such as "const" (As it exists in C++ that is) as it helps the compiler help me reduce inadvertant mistakes today and years down the road during code maintenance.
Anyway, thanks for the advice.
|
|
|
|
|
Apart from what has been mentioned above, the only other way I can think of is to clone the object. Client code will still be able to change values but at least the original object wont change.
Another alternative is to create a read only version of the class and return that.
Architecture is extensible, code is minimal.
|
|
|
|
|
I'm just trying to let other classes have access to the data in the object so cloning would cost too much. The process will need to access the data enough that I only want to pass references around for efficiency.
Creating a read-only version would only be possible if all the data were available to the constructor but unfortunately the process requires a few stages to fully initialize the objects so a few properties need to be accessible by other classes. Since "friend" doesn't exist in C# and since making it "internal" and placing those classes in a different assembly seems like overkill, I'm just going to create an interface to implement that only provides accessors and pass a reference of that interface around to make the const intention apparent in the code.
Someone had suggested using the interface earlier in the other threads and I had come across the same idea on StackOverflow earlier in the day and thought it was a reasonably elegant way to emulate const correctness in C#. However, it turns out to be more work than it should be for something so fundamental to helping the compiler understand the orginal programmers intentions IMHO.
C# had been nothing more than a curiosity to me until recently as I stuck with C/C++ all these years but now that I've attempted to write a few small but serious apps with C#, I'm realizing it's really lacking in some important ways. I've read the posts, blogs, and documentation defending some of the design decisions but I've seen some good counter arguments as well.
Anyway, enough of my ranting. I'll probably need to work with it some more before getting too critical of it.
thanks for the advice.
|
|
|
|
|
Just as a side note: In Visual Studio you can extract an interface from a class by viewing the class in the editor and then Ctl + R,I
Architecture is extensible, code is minimal.
|
|
|
|
|
... and then remove the property set blocks and the functions which could change the data, and access the object via this "read-only interface". Nice idea, and easy to implement!
|
|
|
|
|
Cool. Thanks for the tip.
|
|
|
|
|
Another option is to "wrap" the class in another which has readonly properties that forward to the encapsulated class. Although, I'd only use that option if I were using a class from a third-party codebase. If it's your code, I think the interface option is better, especially since it allows you to cast away the "const" interface. (Although the same could be achieved with the wrapper class.)
"If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy Adams
|
|
|
|
|
I want to either postmessage or sendmessage to tell the software to acquire the USB devices upon startup. I have been getting this "AccessviolationException was unhandled" error during debugging. (Attempting to read or write protected memory. This is often an indcation that other memory is corrupted.
The line where the error dialog box showed pointed to this line after "case HID_API.DBT_DEVICEARRIVAL":
int devType = Marshal.ReadInt32(m.LParam, 4);
Can anyone help me out? How do I fix this?
Code snippet below:
----
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using HID_API_Library;
namespace USB_Box_Application
{
public partial class Form1 : Form
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int PostMessage(int hWnd, int msg, int wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SendMessage(int hWnd, int msg, int wParam, IntPtr lParam);
int[,] deviceInfo = new int[1,2];
Device_Controller dc = new Device_Controller();
DeviceControl[] deviceControl = new DeviceControl[4];
IntPtr[] hwndProcess = new IntPtr[4];
public Point[] PanelLoc = new Point[4];
public Form1()
{
InitializeComponent();
dc.ParentHandle = this.Handle;
dc.RegisterHidNotification(this.Handle);
SendMessage(this.Handle.ToInt32(), HID_API.WM_DEVICECHANGE, HID_API.DBT_DEVICEARRIVAL, (IntPtr)HID_API.DBT_DEVTYP_DEVICEINTERFACE);
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x0001:
{
dc.RegisterHidNotification(this.Handle);
break;
}
case HID_API.WM_DEVICECHANGE:
{
switch (m.WParam.ToInt32())
{
case HID_API.DBT_DEVICEARRIVAL:
{
OnDeviceChange(m);
break;
}
case HID_API.DBT_DEVICEREMOVECOMPLETE:
{
RemoveDevice(ref m);
break;
}
}
break;
}
}
base.WndProc(ref m);
}
void OnDeviceChange( Message m )
{
switch (m.WParam.ToInt32())
{
case HID_API.DBT_DEVICEARRIVAL:
{
int devType = Marshal.ReadInt32(m.LParam, 4);
if (devType == HID_API.DBT_DEVTYP_DEVICEINTERFACE)
{
DEV_BROADCAST_DEVICEINTERFACE1 devInterface = (DEV_BROADCAST_DEVICEINTERFACE1)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_DEVICEINTERFACE1));
string deviceInterface = new string (devInterface.dbcc_name);
if (deviceInterface.Contains("Vid_1238&Pid_5000"))
label2.Text = "USB Box Found!";
if (deviceInterface.Contains("Vid_0483&Pid_0003"))
label2.Text = "Clear Box Found!";
SECURITY_ATTRIBUTES securityAttrib = new SECURITY_ATTRIBUTES();
int usbHandle = HID_API.CreateFile(deviceInterface, HID_API.GENERIC_READ,
HID_API.FILE_SHARE_READ | HID_API.FILE_SHARE_WRITE,
ref securityAttrib, HID_API.OPEN_EXISTING,
HID_API.FILE_FLAG_OVERLAPPED, 0);
if (deviceInterface.Contains("Vid_1238&Pid_5000"))
MessageBox.Show(string.Format("{0}: {1} {2}", "USB Box Found", "Handle =", usbHandle));
if (deviceInterface.Contains("Vid_0483&Pid_0003"))
MessageBox.Show(string.Format("{0}: {1} {2}", "Clear Box Found", "Handle =", usbHandle));
}
break;
}
}
}
-- Modified Thursday, January 27, 2011 8:55 AM
|
|
|
|
|
you are using CP around 8 year and you haven't idea how to use "pre" tag to wrapped Code for make it readability.
Please wrapped your code with "pre" tag
|
|
|
|
|
I haven't used the <pre> tag before... how do i do that? Hey, I'm kinda of old man... LOL
|
|
|
|
|
|
now how's that? I finally figure it out... I will use that from now on. Lesson learned about the use of <pre> for code readability.
|
|
|
|
|
Much better, it is readable now.
Some questions:
1.
Why are you using Marshal.ReadInt32()? I never needed such functions, and I've done my share of device arrival handling.
2.
What is the exact line that fails? or: why don't you have a try-catch inside OnDeviceChange?
3.
Have you searched CodeProject? Detecting Hardware Insertion and/or Removal[^] is an article that may interest you.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
I did check "detecting Hardware Insertion and/or removal... it was written in C++ and I don't quite understand.
On the line after "HID_API.DBT_DEVICEARRIVAL": "int devType = Marshal.ReadInt32(m.LParam, 4);" is where the access memory violation.
I am not expert on hardware interfacing and am currently learning, especially when it comes to WndProc stuff.
I'll try "try-catch".
You said u have done your share of device arrival handling. How do u handle it?
|
|
|
|
|
See Alan's reply.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
Hi,
I'd question the correctness of the the LParam when you send the message
SendMessage(this.Handle.ToInt32(), HID_API.WM_DEVICECHANGE, HID_API.DBT_DEVICEARRIVAL, (IntPtr)HID_API.DBT_DEVTYP_DEVICEINTERFACE);
Code I've seen and used has the LParam as a pointer to a DEV_BROADCAST_HDR structure. You're passing the value HID_API.DBT_DEVTYP_DEVICEINTERFACE (5?) which is never going to a be valid pointer.
[StructLayout(LayoutKind.Sequential)]
internal struct DEV_BROADCAST_HDR {
internal int dbcv_size;
internal DeviceType dbcv_devicetype;
internal int dbcv_reserved;
}
Alan.
|
|
|
|
|
Now its working! Thanks for the help!
|
|
|
|
|
Now one more thing...
The usb device detection & event does work when the software is running.
Now the question is how do i initiate the WM_DEVICECHANGE event at start up? So that when the usb devices are on and when the software is being created (during WM_CREATE) message.
|
|
|
|
|
Alan's reply is perfect. Here is the link[^] to msdn documentation for DBT_DEVICEARRIVAL event. See how lparam is defined.
|
|
|
|
|
Hi there,
I need to be able to zoom in on a label without changing the text size (i.e. feed it a zoom factor, such as 2, and have it enlarge on the screen by that amount).
Basically, a series of labels are part of a component used to set text sizes/layouts on a page. The component needs 'zoom' capability - e.g. zoom to 2x magnification. Clearly, changing the text size would be easy, but this means when the page is saved, the text sizes would have to be changed back ('rescaled') to zoom 1x, which seems awfully messy (esp if the user wants to edit the text size while it's zoomed). Is there an easier/less bothersome way? These do not *HAVE* to be labels, if a solution exists for a similar control (they could be, e.g. uneditable textboxes)...
any help would be greatly appreciated
thanks
Lee
EDIT: I ended up simply having to change the text size, in the 'messy' fashion I described above. It wasn't ideal, but did the job.
modified on Thursday, February 17, 2011 9:08 PM
|
|
|
|
|
The only thing that springs to mind is to have a 'dummy' control that overlies the 'real' one and does all the zooming when anything other than 1x is selected.
Henry Minute
Do not read medical books! You could die of a misprint. - Mark Twain
Girl: (staring) "Why do you need an icy cucumber?"
“I want to report a fraud. The government is lying to us all.”
I wouldn't let CG touch my Abacus!
|
|
|
|