write to usb from two forms

cardmaker

Member
Joined
Jan 12, 2019
Messages
21
Programming Experience
Beginner
hello, i write to usb hid device from form1 but now i need write too from form2 as well.
in form 1 write functions is:
C#:
public static extern bool WriteFile(SafeFileHandle hFile,
                                    byte[] lpBuffer,
                                    uint nNumberOfBytesToWrite,
                                    ref uint lpNumberOfBytesWritten,
                                    IntPtr lpOverlapped);
and WriteHandleToUSBDevice:
C#:
WriteHandleToUSBDevice = CreateFile(DevicePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

and a acess to it in form2 whit:
C#:
 Form1.WriteFile(Form1.WriteHandleToUSBDevice, tmp, 25, ref BytesWritten2, IntPtr.Zero);

but i get an error in form2 ,Error 1 An object reference is required for the non-static field, method, or property 'HID_PnP_Demo.Form1.WriteHandleToUSBDevice' anyone can help?
 
Last edited by a moderator:
So create an object instance of the form you want to work with. In this case; form 1. Looks like your code is in Form2, and you're trying to call Form1. so create an object reference of form1.
Form1 frm1 = new Form1();
frm1. etc
 
So what you're telling the OP to do is use the same code in multiple forms?

If so, I disagree with this approach. That's just creating clutter. If our OP has wrote code in Form1, and wants to access it from Form2, then our OP should be instantiating a new form of that type.

Moreover, and more logical, If you want to do something like that, at least create a static class and insert that code into your static class and change the access modifiers to public as well as keeping them static. Then you can use the same code in any form providing you create a new class file for that code.
 
So what you're telling the OP to do is use the same code in multiple forms?
No, I'm telling them to not put the code in any form. Put it in a dedicated class and then use that class in each form. As the external method is static, the handle probably ought to be exposed via a static member too.
 
Ok that's fine. It sounded like you were advising copying / pasting the same code into both forms on post 3 as a solution, and also why i asked. Yes, moving them to a separate static class as I suggested on post 4 would be best.
 
Solved it how, and what solution did you settle on, as I proposed two solutions?

The later would have been a better option. You should move your code into a new class file and make it static. Then move your code above and all handlers into that class file. Then you can call it by the class name and method name directly without instantiating anything. My first solution is just the obvious and easiest, but it's not the most logical, if you want to use the same code on both forms.
 
Back
Top Bottom