Friday, May 6, 2011

Displaying a bitmap on a "BUTTON" class window in WIN32

Edit: I think the WM_CREATE message isn't sent during the creation of child windows (namely my button). So by calling SendMessage during WM_CREATE, I'm sending a message to a window that hasn't been created yet. The solution for now is to call SendMessage() during the WM_SHOWWINDOW message. Do child windows send WM_CREATE messages at creation?

Why isn't the bitmap displaying on the button? The bitmap is 180x180 pixels.

I have a resource file with:

Bit BITMAP bit.bmp

I then create the main window and a child "BUTTON" window with:

HWND b, d;

b = CreateWindow(L"a", NULL, WS_OVERLAPPEDWINDOW, 0, 0, 500, 500, 0, 0, 
                  hInstance, 0);

d = CreateWindow(L"BUTTON", NULL, WS_CHILD | WS_VISIBLE | BS_BITMAP, 
                 10, 10, 180, 180, b, 200, hInstance, 0);

Then, in my windows procedure, I send the "BUTTON" window the "BM_SETIMAGE" message with:

HBITMAP hbit; 

case WM_CREATE:    // It works if I change this to: case WM_SHOWWINDOW 

hbit = LoadBitmap(hInstance, L"Bit");

SendMessage(d, BM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)hbit);

LoadBitmap() is returning a valid handle because It isn't returning NULL, and I'm able to display the bitmap in the client area using the BitBlt() function. So I'm either not sending the message correctly, or I'm not creating the "BUTTON" window correctly.

What am I doing wrong?

Thanks!

From stackoverflow
  • How are you verifying that WM_CREATE isn't getting called? Since BUTTON isn't your window class (but rather defined by the OS) it owns the WndProc for the window, not you - therefore WM_CREATE shouldn't be called for the button in your code, because BUTTON isn't your class.

    If you want to receive messages for the button, you'll have to subclass it, and then provide your own WndProc.

    tyler : What I tried to explain in my edit is that WM_CREATE is only sent to the main window, not to the button. I wasn't saying that WM_CREATE isn't being sent. I thought that maybe my WndProc would recieve WM_CREATE messages during the creation of its child windows. It does after all receive WM_COMMAND messages that were generated from its child button window.
  • The window procedure for for your window class "a" gets called with WM_CREATE when a window of that class is created. This is during your first call to CreateWindow, which is before you create the child BUTTON window. WM_CREATE means "you are being created" - it doesn't mean "a child is being created".

    The solution is to call d = CreateWindow(L"BUTTON"...) in the WM_CREATE handler for class "a":

    case WM_CREATE:
        d = CreateWindow(L"BUTTON", NULL, WS_CHILD | WS_VISIBLE | BS_BITMAP, 
                         10, 10, 180, 180, hwnd, 200, hInstance, 0);
        hbit = LoadBitmap(hInstance, L"Bit");
        SendMessage(d, BM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)hbit);
    
    tyler : Thanks. I thought the same thing but when I tried it I actually get no button at all (not even an outline). The only thing that has worked has been to put the the SendMessage() in WM_SHOWWINDOW.
    RichieHindle : I bet that's because you're calling d = CreateWindow(..., b, ...) rather than d = CreateWindow(..., hwnd, ...) - remember, you're within the first call to CreateWindow, so b hasn't yet been assigned to.
    tyler : Wow, brilliant..that completely makes sense. Thanks man.
  • take a look here:

    http://winapi.foosyerdoos.org.uk/info/user_cntrls.php

UIImageView and UIImage: How can I tweak the most performance out of them?

First: I've implement a fairly complex scrolling mechanism for images, that allows to scroll over a few hundred thousands (theoretically) in one single scroll view. This is done by preloading small portions upon scrolling, while re-using all UIImageViews. Currently all I do is to assign new created UIImage objects to those re-used UIImageViews.

It might be better if it's possible to also re-use those UIImage objects by passing new image data to them.

Now the problem is, that I am currently using the -imageNamed: method. The documentation says, that it caches the image.

Problems I see in this case with -imageNamed: As the image gets scrolled out of the preloading range, it's not needed anymore. It would be bad if it tries to cache thousands of images while the user scrolls and scrolls and scrolls. And if I would find a way to stuff new image data into the UIImage object for re-using it, then what happens with the old image that was cached?

So there is one method left, that seems interesting: -initWithContentsOfFile:

This does not cache the image. And it doesn't use -autorelease, which is good in this case.

Do you think that in this case it would be better to use -initWithContentsOfFile:?

From stackoverflow
  • Only a benchmark can tell you for sure. I'm inclined to think that UIImage image caching is probably extremely efficient, given that it's used virtually everywhere in the OS. That said with the number of images you're displaying, your approach might help.

Which is not a reason to create a custom exception?

Hello,

Recently I took a test at brainbench and got not a bad result (something like 4.5, master degree). I didn't know the answer only on 1 question (the rest I was sure about or at least I thought I knew the correct answer :) ). The question is:

Which one of the following is NOT a reason to create custom exceptions?

Choice 1
To insert a strong label for later inspection
Choice 2
To strongly-type the purpose of a particular exception
Choice 3
To allow for remote serialization
Choice 4
To process common steps when an exception is created
Choice 5
To add custom properties for custom data propagation

I answered "4" - To process common steps when an exception is created. Which one you think is correct?

From stackoverflow
  • Choice 3. The base exception either already supports remoting, or else you deriving from it won't add remoting.


    The "exception" Marc mentions in a comment is as follows; I think it's not what the test writers had in mind:

    In a WCF service, you can allow an unhandled exception to propagate out of the service. WCF will turn it into a SOAP Fault, which may or may not contain details of the unhandled exception, depending on configuration.

    Better, would be to recognize certain sets of exceptions and translate them deliberately into SOAP Faults. For instance, a service that operates on database entities could expect that sometimes an entity would not be found; sometimes an attempt to add a new entity would result in a duplicate; sometimes an update attempt would have resulted in an invalid state. Such a service might decide to expose a NotFoundFault, DuplicateItemFault, and InvalidStateFault.

    The service would define the three faults as Data Contracts to define their contents:

    [DataContract]
    public class FaultBase {
        [DataMember]
        public string ErrorMessage {get;set;}
    }
    
    [DataContract]
    public class NotFoundFault : FaultBase {
        [DataMember]
        public int EntityId {get;set;}
    }
    
    [DataContract]
    public class DuplicateItemFault : FaultBase {
        [DataMember]
        public int EntityId {get;set}
    }
    
    [DataContract]
    public class InvalidStateFault : FaultBase {
    }
    

    You would then indicate that particular operations can return such faults:

    [OperationContract]
    [FaultContract(typeof(NotFoundFault))]
    public Entity GetEntityById(int id)
    

    Finally, you might wrap an exception from the DAL in such a way that WCF will return the particular fault instead:

        try {
            return DAL.GetEntity<Entity>(id);
        }
        catch (DAL.NoSuchEntityException ex)
        {
            throw new FaultException<NotFoundFault>(
                new NotFoundFault {EntityId = ex.Id, ErrorMessage = "Can't find entity"});
        }
    

    I think the test developer was trying to get you to think that something special needs to be done in order for an exception to be serialized for remoting to a different AppDomain. This will not be the case if the custom exception was properly implemented, as the supplied .NET exception classes are all serializable. Thus, the ability to serialize is not an excuse to create a custom exception, as the base class should already be serializable.

    nightcoder : Yes, maybe, I thought about it already before writing the question..
    victor hugo : I vote 3 too! All the other ones are reasons for DO create a custom exception
    Marc Gravell : Re 3 - that may be true for .NET "remoting", but for WCF 3 *is* a reason to replace an exception with a "fault" (a special class of exception) for serialization purposes.
    John Saunders : @Marc: I know that, and you know that, but did the creators of the test know that? I bet not, and the context was more general.
  • I'll actually agree with 4 being the wrong one: To process common steps when an exception is created.

    Exceptions are not supposed to execute "steps" when they're created, but rather inform the system that an exceptional situation has been created for which the current class (and possibly module) doesn't know how to address.

    If executing common steps is necessary for the proper execution of a function, that functionality should be included in the code itself, not separated into an exception.

    Marc Gravell : I'll buy that...
    Dan C. : If you think of cleanup actions as "common steps when an exception is created" and if you do not consider "created" literally, it might make sense. Brainbench tests have sometimes a misleading wording...
  • While using WCF services, we did have to create custom exceptions for serializations. So 3 can't be the correct answer.

    nightcoder : PS. The test was "C# 2.0 Fundamentals" so I think it can't consider WCF aspects.
    Rashmi Pandit : Ok ... the same would apply for web services though

How to add debug assemblies to my Silverlight 2 application?

So I know now that the debug assemblies have been intentionally left out of the Silverlight runtime to save space. For that reason I get good detailed error messages on my local machine that has the Silverlight SDK on it, but I don't on a computer with the runtime only. I get the ubiquitous, "Debugging resource strings are unavailable."

Unfortunately my requirements are a bit unique. I need to include the debug assembly (not sure which one yet) that will give me details of a regular expression error. And so essentially I want to include the dll in the xap if I can.

The problem is that I can't seem to do this. I've tried adding the debug dll's as references and setting them to "copy local." And I've tried adding them into the project as content. But in fact, with either method the xap hardly grows in size and the error message doesn't change.

Any ideas?

From stackoverflow
  • You'll still need the actual Silverlight Developer Runtime to be installed (thus you get the errors etc on the machine you had the SDK installed on). Adding the debug assembly into a production solution and accessing it via the non-developer runtime isn't possible.

    Scott Barnes / Rich Platforms Product Manager / Microsoft.

    Steve Wortham : Thanks Scott. That's what I was beginning to think. I suppose the one other option is to perform a try/catch around the regex, and then if there's an error then send the regex to a web service that then replies with the error details. It's not exactly my idea of the perfect solution, but I may do something like that. If I do all of that asynchronously it should still make for a decently responsive UI experience. By the way, this is all for www.regexhero.com Thanks again, Steve
    Scott : Is this still a limitation with Silverlight 3.0 and Silverlight 4.0? I ask, because it becomes a problem when doing validation as these strings are sometimes used in the ValidationSummary control.
  • So my solution to the problem was essentially to give up on what I was trying to do. Instead, I'm now calling a web service whenever an exception occurs around the regex. That web service has a function I made called GetRegexError.

    Here's the code for it:

    <WebMethod()> _
    Public Function GetRegexError(ByVal strRegex As String, ByVal _regexOptions As RegexOptions) As String
        Try
         Dim _regex As New Regex(strRegex, _regexOptions)
        Catch ex As Exception
         Return ex.Message
        End Try
    
        Return ""
    End Function
    

    This is now implemented in Regex Hero. Thank you Scott for the help.

  • Hi Scot, I'm facing this problem now and if I don't have a solution at server side. Every client'll need to install Silverlight Developer Runtime manually So I think it's not good solution.

    @Steve: If can, please post your example solve this problem here.

    Thanks.

    Steve Wortham : My answer is right above (or below) yours.

CALayer and CGGradientRef anti-aliasing?

Hello all. I'm having an odd issue with CALayer drawing for the iPhone. I have a root layer which adds a bunch of sublayers representing "bubbles". The end result is supposed to look something like this:

http://www.expensivedna.com/IMG_0018.PNG

The problem is that I can't seem to get the layer to anti-alias (notice the jaggies on the bubbles). My code overwriting drawInContext for the bubble CALayer is as follows:

- (void)drawInContext:(CGContextRef)theContext{
CGContextSetAllowsAntialiasing(theContext, true);
CGContextSetShouldAntialias(theContext, true);

size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 1.0, 1.0, 1.0, 0.5,  // Start color
        1.0, 1.0, 1.0, 0.0 }; // End color
CGColorSpaceRef rgbColorspace = CGColorSpaceCreateDeviceRGB();
CGGradientRef glossGradient = 
CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);

CGPoint topCenter = CGPointMake(25, 20);
CGPoint midCenter = CGPointMake(25, 25);
CGContextDrawRadialGradient(theContext, glossGradient, midCenter, 20, topCenter, 10, kCGGradientDrawsAfterEndLocation);

}

Now the really odd thing is that if I slightly alter the drawing code to only draw normal red circles as follows:

- (void)drawInContext:(CGContextRef)theContext{
CGContextSetAllowsAntialiasing(theContext, true);
CGContextSetShouldAntialias(theContext, true);

CGContextSetFillColorWithColor(theContext, [UIColor redColor].CGColor);
CGContextFillEllipseInRect(theContext, CGRectMake(0, 0, 40,40));
}

Everything seems to antialias OK:

http://www.expensivedna.com/IMG_0017.PNG

I can't seem to figure out this seemingly odd behavior. Am I missing some difference between antialiasing gradients and normal circles?

Thanks guys.

From stackoverflow
  • maybe try dropping out the kCGGradientDrawsAfterEndLocation? It might be doing something weird with the alpha

  • Jeff - make topCenter a bit further out and use CGContextClipToMask with a circular mask.

    Edit: Actually a much much better way to do it is to use a vector clipping path using CGContextClip.

    Edit 2: Sample code:

    CGContextAddEllipseInRect(theContext, CGRectMake(20, 20, 10, 10));
    CGContextClip(theContext);
    

    Add this before you draw your gradient, and draw it a bit further out.

  • Thanks guys. So it turns out that the answer is a combination of your two answers (coob and Alex). Basically it seems like the CGDrawRadialGradient function only has aliasing at the starting circle, not the ending one. Since I want aliased "edges" on both, I first set the function to draw from the inside out which takes care of the first "edge", but produces the following:

    Step 1

    Then, I clip the image as suggested by coob and that gives a nice aliasing around the final edge of the bubble:

    Step 2

    Looks good enough for me!

    - (void)drawInContext:(CGContextRef)theContext{
    CGContextSetAllowsAntialiasing(theContext, true);
    CGContextSetShouldAntialias(theContext, true);
    
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = { 1.0, 1.0, 1.0, 0.0,  // Start color
         1.0, 1.0, 1.0, 0.5 }; // End color
    CGColorSpaceRef rgbColorspace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef glossGradient = 
    CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
    
    CGContextAddEllipseInRect(theContext, CGRectMake(5, 5, 40, 40));
    CGContextClip(theContext);
    
    CGPoint topCenter = CGPointMake(25, 20);
    CGPoint midCenter = CGPointMake(25, 25);
    CGContextDrawRadialGradient(theContext, glossGradient, topCenter, 10, midCenter, 20, kCGGradientDrawsAfterEndLocation);
    

    }

how to protect the ws discovery ad hoc network from man-in-the-middle attacks

the ws-discovery specifications explains how to protect your network from

  1. message alteration
  2. Denial of service
  3. replay
  4. spoofing

but what about man-in-the-middle attack?

From stackoverflow
  • As far as I understand, The "message alteration" mitigation, that is signing the messages, is protecting the interaction from man-in-the-middle attack. If you can verify the source of the message and it authenticity by the sender unique signature, then any one trying to pretend to be legitimate sender wan't be able to do so.

    Disclaimer: I am not security expert.

  • The idea behind a Man in the Middle Attack(Wikipedia.org), is that your network is compromised and the attacker can intercept, view, and modify traffic between all members. The most basic step towards preventing this is to encrypt the network with WPA (at the minimum) and keep the access points locked down. Your goal should be to first prevent an attacker from getting into the network. The second layer of defense you could employ is to use some form of encryption for all the traffic between parties on the network (perhaps something other than public/private) so even if the network is compromised, the traffic will still not be intelligible to the attacker.

    Disclaimer: I am also not a security expert.

  • ws security secures that when you sign the message, as it uses the private key to encrypt and then the reciept decrypt using the public key; so a man in the middle wont be able to interfere.

Fogbugz like dropdown menu

I am searching for a jquery plugin to get a fogbugz like dropdown menu so that you can type in the dropdown menu.

This is what it should look like: http://dl.getdropbox.com/u/5910/Jing/2009-05-10_0937.swf ( the old video http://dl.getdropbox.com/u/5910/Jing/2009-05-10_0055.swf )

All the answers have been not giving me the typing part any other suggestions?

EDIT: I found something a bit like it: http://phone.witamean.net/sexy-combo/examples/index.html but there are a couple things that bug me: it doesn't select the whole string we clicking in the textbox and the dropbox doesn't show all options when clicking on the triangle

I found a working demo but its from ext :( http://extjs.com/deploy/dev/examples/form/combos.html not jquery... but it has all the features I neet

From stackoverflow
  • I haven't found one yet that has both auto-complete and the combo drop down arrow. However, this plug-in is close.

  • That's usually called a combobox, you can find a nice jQuery one here:

    http://jonathan.tang.name/code/jquery_combobox

    Thomaschaaf : but it doesn't have the writing part
    James Avery : changed the link to a better one (based on jQuery UI too)
    Thomaschaaf : Thanks a bunch I wanted to start writing my own tomorrow now I don't have to :)